今天,当我在ASP.NET MVC2中做了几个<%=Html.LabelFor(m=>m.MyProperty)%>
和使用System.ComponentModel
中的[DisplayName("Show this instead of MyProperty")]
属性时,我感到困惑。
事实证明,当我将该属性放在被覆盖的属性上时,LabelFor似乎没有注意到这一点。
但是,[Required]
属性在被覆盖的属性上工作得很好,并且生成的errormessage实际上使用了DisplayNameAttribute。
这是一些微不足道的示例代码,更现实的情况是我有一个独立于视图模型的数据库模型,但为了方便起见,我想继承数据库模型,添加只读属性,并用UI的属性装饰视图模型。
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; }
}
强类型的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>
然后,在查看页面时,标签将显示为"PleaseOverrideMe“(使用DisplayNameAttribute而不是)和"This property exists in EditModel”(使用 DisplayNameAttribute)。
如果我使用空值进行post,则会使用此ActionMethod触发验证:
[HttpPost]
public ActionResult Edit(EditModel model)
{
if (!ModelState.IsValid)
return View(model);
return View("Thanks");
}
<%= Html.ValidationMessageFor(model => model.PleaseOverrideMe) %>
实际上使用了[DisplayName("This should be as label for please override me!")]
属性,并生成了默认的错误文本:“这应该是标签,请覆盖我!字段是必需的。”
会有友善的灵魂来解释这件事吗?
发布于 2010-04-01 05:14:32
Model binding and metadata using the strongly-typed helpers looks at the declared, rather than the runtime, type of the model。我认为这是一个bug,但显然MVC团队不同意我的观点,因为我在这个问题上的Connect问题以"By Design“结束。
发布于 2010-11-05 09:16:05
我在使用DisplayName(“配置文件名称”)时遇到了这个问题,而使用[Display(Name = "Profile Name")]
解决了我的问题。我不确定这是否有用。
前者来自System.ComponentModel
,后者来自System.ComponentModel.DataAnnotations
。
发布于 2010-04-28 03:21:20
当我将局部视图强类型化为接口时,我也遇到了同样的问题。该接口定义了一个DisplayName
,实现该接口的类试图覆盖它。我发现让它遵守覆盖的唯一方法是输入实现类。我必须更改视图的模型类型或强制转换。不幸的是,这完全否定了使用接口作为模型类型的好处。我猜我最终会得到每个实现类的某种级别的重复视图标记,而不是在强类型的"helpers“中进行强制转换。
在这种类型的变通方法甚至有一点帮助的可能性很小(不会让我产生希望),这里有一个例子。当然,对于试图重写名称的所有可能的实现类,都有处理这种情况的方法,但它肯定比应该的更麻烦。
public interface IAddressModel {
...
[DisplayName("Province")]
public string Province { get; set; }
...
}
public class UsAddressModel : IAddressModel {
...
[DisplayName("State")]
public string Province { get; set; }
...
}
<%= Html.LabelFor(m => m.State) %> <!--"Province"-->
<%= Html.LabelFor(m => (m as UsAddressModel).State) %> <!--"State"-->
https://stackoverflow.com/questions/2555759
复制相似问题