ASP.NET MVC: Accessing ViewModel Attributes on the view

时光怂恿深爱的人放手 提交于 2019-12-07 06:58:23

问题


Is there any way to access any attributes (be it data annotation attributes, validation attributes or custom attributes) on ViewModel properties from the view? One of the things I would like to add a little required indicator next to fields whose property has a [Required] attribute.

For example if my ViewModel looked like this:

public class MyViewModel
{
    [Required]
    public int MyRequiredField { get; set; } 
}

I would want to do something in the EditorFor template like so:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<int?>" %>

<div class="label-container">
    <%: Html.Label("") %>

    <% if (PROPERTY_HAS_REQUIRED_ATTRIBUTE) { %>
        <span class="required">*</span>
    <% } %>
</div>
<div class="field-container">
    <%: Html.TextBox("") %>
    <%: Html.ValidationMessage("") %>
</div>

回答1:


The information you're looking for is in ViewData.ModelMetadata. Brad Wilson's blog post series on Templates should explain it all, especially the post on ModelMetadata.

As far as the other ValidationAttributes go, you can access them via the ModelMetadata.GetValidators() method.

ModelMetadata.IsRequired will tell you if a complex type (or value type wrapped in Nullable<T>) is required by a RequiredAttribute, but it will give you false positives for value types that are not nullable (because they are implicitly required). You can work around this with the following:

bool isReallyRequired = metadata.IsRequired 
    && (!metadata.ModelType.IsValueType || metadata.IsNullableValueType);

Note: You need to use !metadata.ModelType.IsValueType instead of model.IsComplexType, because ModelMetadata.IsComplexType returns false for MVC does not consider to be a complex type, which includes strings.




回答2:


I would suggest not doing that way because you're adding logic in the view which is a bad practice. Why don't you create a HtmlHelper or LabelExtension, you can call ModelMetaProvider inside the method and find out whether the property has Required attribute decorated?



来源:https://stackoverflow.com/questions/7508037/asp-net-mvc-accessing-viewmodel-attributes-on-the-view

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