ASP.NET MVC: Accessing ViewModel Attributes in a View

Is there a way to access any attributes (whether data annotation attributes, validation attributes, or user attributes) in the ViewModel properties from the view? One of the things that I would like to add is a bit of the required indicator next to the fields whose property has the [Required] attribute.

For example, if my ViewModel looked like this:

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

I would like to do something in the EditorFor template like this:

 <%@ 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> 
+4
source share
2 answers

The information you are looking for is in ViewData.ModelMetadata . The Brad Wilson template blog series should explain all this, especially the post on ModelMetadata .

As for the other ValidationAttributes, you can access them using the ModelMetadata.GetValidators() method.

ModelMetadata.IsRequired will tell you if RequiredAttribute requires a complex type (or a value type wrapped in Nullable<T> ), but it will provide you with false positives for value types that are not null (since they are implicitly mandatory). You can get around this with the following:

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

Note: you need to use !metadata.ModelType.IsValueType model.IsComplexType instead of model.IsComplexType , because ModelMetadata.IsComplexType returns false for MVC, is not considered a complex type that includes strings.

+7
source

I would suggest not doing this because you are adding logic to the view, which is bad practice. Why don't you create an HtmlHelper or LabelExtension, you can call ModelMetaProvider inside the method and find out if the property has the required attribute?

+1
source

All Articles