get unobtrusive validation attributes by ViewModel Type

Viewed 68

I need something like

var dict = html.GetUnobtrusiveValidationAttributes<ViewModel1>(propName);

and I got it working 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 is that I have to call this in a view with @model in order for it to work, otherwise attributes will always be empty

@model MyVM // I want to make it work without this line
@Html.GetVld<MyVM>()

I tried doing: var html2 = new HtmlHelper<TModel>(html.ViewContext, html.ViewDataContainer) and using html2 instead of html but it won't help.

0 Answers
Related