开发者

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

开发者 https://www.devze.com 2023-03-26 04:47 出处:网络
Suppose I have a view model with a pr开发者_运维知识库operty that looks something like this: [Required]

Suppose I have a view model with a pr开发者_运维知识库operty 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.


Model metadata is available from ViewData, ie.

ViewData.ModelMetadata.GetDisplayName()


This solution worked well for me by creating a helper method to work out if the [Required] attribute is present or not:

public static MvcHtmlString RequiredSymbolFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression,
    string symbol = "*",
    string cssClass = "editor-field-required")
{
    ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

    if (modelMetadata.IsRequired)
    {
        var builder = new TagBuilder("span");
        builder.AddCssClass(cssClass);
        builder.InnerHtml = symbol;

        return new MvcHtmlString(builder.ToString(TagRenderMode.Normal));
    }

    return new MvcHtmlString("");
}

http://www.kristofclaes.be/blog/2011/08/26/an-htmlhelper-to-display-if-a-field-is-required-or-not-in-aspnet-mvc-3/

https://web.archive.org/web/20130711024856/http://www.kristofclaes.be/blog/2011/08/26/an-htmlhelper-to-display-if-a-field-is-required-or-not-in-aspnet-mvc-3/

0

精彩评论

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