Search code examples
c#asp.net-mvc-3templatesdata-annotationseditorfor

Is there a way to access DataAnnotations when building MVC3 EditorFor templates?


Suppose I have a view model with a property that looks something like this:

[Required]
[Display(Name = "Your name")]
public string Name { get; set; }

I want to build an EditorFor template that looks something like this:

<label>
    @Model.DisplayName
    @if (Model.Required)
    {
        <span class="required">*</span>
    }
<label>
@Html.TextBoxFor(model => model)

Obviously, the above will fail (Model.Required and Model.DisplayName), but I'm just using that as an example of what I'm trying to do.

Is this possible?

Thanks in advance.


Solution

  • Model metadata is available from ViewData, ie.

    ViewData.ModelMetadata.GetDisplayName()