How to use Html.GetUnobtrusiveValidationAttributes()

雨燕双飞 提交于 2019-11-29 04:16:28
Moeri

For those still looking for an answer, this works for me:

public static IDictionary<string, object> UnobtrusiveValidationAttributesFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> propertyExpression)
{
    var propertyName = html.NameFor(propertyExpression).ToString();
    var metadata = ModelMetadata.FromLambdaExpression(propertyExpression, html.ViewData);
    var attributes = html.GetUnobtrusiveValidationAttributes(propertyName, metadata);
    return attributes;
}

Note that I'm using .Net MVC 4, you don't have the html.NameFor method in MVC 3. However, I believe this can be done in MVC 3 with the following method:

var propertyName = ExpressionHelper.GetExpressionText(propertyExpression);

You can use it inline

Example for select element

<select name="@Html.NameFor(m=> m.MyProperty)"
        id="@Html.IdFor(m=> m.MyProperty)"
        @Html.Raw(string.Join(" ", Html.GetUnobtrusiveValidationAttributes(Html.NameFor(m => m.MyProperty).ToString()).Select(x => x.Key.ToString() + "=\"" + x.Value + "\"")))
>
counsellorben

Here is a link to an answer I posted, showing an HtmlHelper I wrote to provide unobtrusive validation for dropdownlists: MVC 3 dropdownlist validation not working for complex view model

UPDATE

Are you trying to get the attributes in an HtmlHelper, or in-line in your view?

Assuming you are trying to get the attributes in your view, that is the problem.

First, you need to understand that ModelMetadata does not represent a single object available across your entire model. Rather, it represents the metadata for a particular element, be it your model, or any property within the model. A better descriptive name would be ObjectMetadata, since ModelMetadata is the metadata for a specified object, be it a model, a nested model, or a specific property.

ModelMetadata in the view is only the metadata for the top-level model. You must get the ModelMetadata for the property to which the dropdownlist is bound. If you use a helper, then the helper is passed the correct ModelMetadata as a matter of course. If you use your view, you need to engage in some gymnastics to get the correct ModelMetadata, see for example my answer here: Validating and editing a “Changeable”/optional type in Asp.net MVC 3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!