MVC 中公共字段与属性的数据注释
为什么 DataAnnotations 不适用于公共字段?示例:
namespace Models
{
public class Product
{
[Display(Name = "Name")]
public string Title; // { get; set; }
}
}
public ActionResult Test()
{
return View(new Models.Product() { Title = "why no love?" });
}
@Html.LabelFor(m => m.Title) // will return 'Title' if field, or 'Name' if property
@Html.DisplayFor(m => m.Title)
如果 Title 是一个字段,则 Display 属性似乎不起作用。如果标题更改为属性,它将按预期显示“名称”。
在此示例中,仅更改属性似乎很容易,但我尝试使用 F# 中的类型,其中它们被编译为具有字段而不是属性的类。
这已在 ASP.NET 4 和 MVC RC 3 中进行了测试。
Why don't DataAnnotations work on public fields? Example:
namespace Models
{
public class Product
{
[Display(Name = "Name")]
public string Title; // { get; set; }
}
}
public ActionResult Test()
{
return View(new Models.Product() { Title = "why no love?" });
}
@Html.LabelFor(m => m.Title) // will return 'Title' if field, or 'Name' if property
@Html.DisplayFor(m => m.Title)
If Title is a field, then the Display attribute seems to have no effect. If Title is changed to a property, it works as expected as displays "Name".
It would seem easy in this example to just change to a property, but I am trying to use the types from F# where they get compiled to a class with fields and not properties.
This was tested in ASP.NET 4 and MVC RC 3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DataAnnotations 不适用于字段的原因是,用于检索属性 (
TypeDescriptor
) 的类反射机制仅支持属性。虽然这并不容易,但如果有足够的需求,我们可以考虑将其应用于现场。
The reason why DataAnnotations do not work with fields is because the reflection-like mechanism that is used to retrieve the attributes (
TypeDescriptor
) only supports properties.While it would not be easy, we could look into making this work with fields if there is enough demand.