Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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>
like image 520
ajbeaven Avatar asked Sep 21 '11 23:09

ajbeaven


1 Answers

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.

like image 186
Bennor McCarthy Avatar answered Sep 19 '22 23:09

Bennor McCarthy