开发者

ASP.NET MVC: Accessing ViewModel Attributes on the view

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 Ed开发者_StackOverflowitorFor 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>


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜