在公共领域VS在MVC性能DataAnnotations [英] DataAnnotations on public fields vs properties in MVC
问题描述
为什么不DataAnnotations在公共领域工作?例如:
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".
这似乎很容易在这个例子中,只是改变一个属性,但我想从使用F#类型,他们会被编译到类的字段,而不是属性。
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.
这是在ASP.NET 4和MVC 3 RC测试。
This was tested in ASP.NET 4 and MVC RC 3.
推荐答案
之所以DataAnnotations不下地干活是因为用于检索的属性( TypeDescriptor 反射般的机制code>)仅支持属性。
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.
这篇关于在公共领域VS在MVC性能DataAnnotations的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!