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>
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.IsRequiredwill tell you if a complex type (or value type wrapped inNullable<T>) is required by aRequiredAttribute, 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:Note: You need to use
!metadata.ModelType.IsValueTypeinstead ofmodel.IsComplexType, becauseModelMetadata.IsComplexTypereturns false for MVC does not consider to be a complex type, which includes strings.