aspnet / AspNetWebStack

ASP.NET MVC 5.x, Web API 2.x, and Web Pages 3.x (not ASP.NET Core)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

can we get unobtrusive validation attributes by ViewModel Type

omuleanu opened this issue · comments

I know there's
html.GetUnobtrusiveValidationAttributes(name, metadata)
and this method only works when html was called by the EditorFor helper
I need something like
var dict = html.GetUnobtrusiveValidationAttributes<ViewModel1>(propName);
(and I would call it in a loop for each viewmodel property)
is it possible to achieve this ?

I managed to do it like this:

        public static IHtmlString GetVld<TModel>(this HtmlHelper html)
        {
            ...

            foreach (var prop in typeof(TModel).GetProperties())
            {
                var attributes = new Dictionary<string, object>();
            
                Func<string, ModelMetadata, IEnumerable<ModelClientValidationRule>> ClientValidationRuleFactory 
                    = (name, metadata) => ModelValidatorProviders.Providers.GetValidators(metadata ?? ModelMetadata.FromStringExpression(name, html.ViewData), html.ViewContext).SelectMany(v => v.GetClientValidationRules());

                var clientRules = ClientValidationRuleFactory(prop.Name, null);
                UnobtrusiveValidationAttributesGenerator.GetValidationAttributes(clientRules, attributes);

the only problem now is that the call to @Html.GetVld<MyVM>() has to be in a view with @model TModel, otherwise it doesn't work
for example doing:
var html2 = new HtmlHelper<TModel>(html.ViewContext, html.ViewDataContainer); and after using html2 instead of html won't help

commented

Thanks for contacting us. This repo is in maintenance mode and we don't actively monitor it. That also means we handle only most critical bug fixes and security issues.
This one seem to be a question and we recommend following up in StackOverflow instead. Most probably, though, you've already found a solution for this.