繁体   English   中英

构建MVC3 EditorFor模板时,是否可以访问DataAnnotations?

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

假设我有一个视图模型,其属性看起来像这样:

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

我想构建一个看起来像这样的EditorFor模板:

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

显然,以上操作将失败( Model.RequiredModel.DisplayName ),但我只是以该示例为例进行尝试。

这可能吗?

提前致谢。

模型元数据可从ViewData ,即。

ViewData.ModelMetadata.GetDisplayName()

此解决方案对我来说效果很好,方法是创建一个辅助方法来确定是否存在[Required]属性:

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-或-未在-ASPNET-MVC-3 /

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM