想知道为什么在重写的属性上的LabelFor中忽略DisplayName属性

Las*_*ntz 19 validation attributes asp.net-mvc-2

今天我<%=Html.LabelFor(m=>m.MyProperty)%>在使用ASP.NET MVC 2中的几个并使用[DisplayName("Show this instead of MyProperty")]来自的属性时感到困惑System.ComponentModel.

事实证明,当我将属性放在重写的属性上时,LabelFor似乎没有注意到它.
但是,该[Required]属性在重写的属性上工作正常,并且生成的errormessage实际上使用DisplayNameAttribute.

这是一些简单的示例代码,更现实的情况是我有一个与viewmodel分开的databasemodel,但为了方便起见,我想继承databasemodel,添加View-only属性并使用UI的属性装饰viewmodel .

public class POCOWithoutDataAnnotations
{
    public virtual string PleaseOverrideMe { get; set; }        
} 
public class EditModel : POCOWithoutDataAnnotations
{
    [Required]
    [DisplayName("This should be as label for please override me!")]
    public override string PleaseOverrideMe 
    {
        get { return base.PleaseOverrideMe; }
        set { base.PleaseOverrideMe = value; }
    }

    [Required]
    [DisplayName("This property exists only in EditModel")]
    public string NonOverriddenProp { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

强类型ViewPage<EditModel>包含:

        <div class="editor-label">
            <%= Html.LabelFor(model => model.PleaseOverrideMe) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.PleaseOverrideMe) %>
            <%= Html.ValidationMessageFor(model => model.PleaseOverrideMe) %>
        </div>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.NonOverriddenProp) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.NonOverriddenProp) %>
            <%= Html.ValidationMessageFor(model => model.NonOverriddenProp) %>
        </div>
Run Code Online (Sandbox Code Playgroud)

然后,在查看页面时,标签显示为"PleaseOverrideMe"(使用DisplayNameAttribute)和"此属性仅存在于EditModel中"(使用 DisplayNameAttribute).
如果我使用空值发布,则使用此ActionMethod触发验证:

    [HttpPost]
    public ActionResult Edit(EditModel model)
    {
        if (!ModelState.IsValid)
            return View(model);
        return View("Thanks");
    }
Run Code Online (Sandbox Code Playgroud)

<%= Html.ValidationMessageFor(model => model.PleaseOverrideMe) %>实际使用[DisplayName("This should be as label for please override me!")]属性,并产生默认ERRORTEXT "的这应该是作为标签,请忽略我!是必填字段."

一些友好的灵魂会对此有所了解吗?

Cra*_*ntz 12

使用强类型帮助程序的模型绑定和元数据会查看模型的声明类型而不是运行时类型.我认为这是一个错误,但显然MVC团队不同意我,因为我的Connect问题被关闭为"By Design".

  • 好吧,我会尝试将其作为一个错误@ Connect并为"By Design"做好准备.谢谢! (4认同)

Jos*_*yes 11

我使用[DisplayName("Profile Name")]遇到了这个问题,而是使用[Display(Name = "Profile Name")]了解决我的问题的问题.我不确定这是否有用.

前者来自System.ComponentModel后者,后者来自System.ComponentModel.DataAnnotations.

  • 六年后,这修复了MVC 5中的同样问题:) (3认同)