我正在使用 MVC3,并使用 Entity Framework 4.0 实体作为我的模型。到目前为止,就将其用作模型而言,一切都运行良好(所有增删改查操作/页面生成都是开箱即用的)。不过,我想知道如何获得与手动生成模型时相同的强大标签和验证信息?
这是一个例子来说明我的意思。这是由示例 MVC3 项目生成的类:
public class LogOnModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
通过上面的示例,您可以指定字段标签中呈现的内容(显示)以及要使用的字段类型(密码)。但是,当我尝试使用 Entity Framework 并将其推送到下面的 View 时,我看到自动生成的标签只是字段名称,而不是我希望用户看到/必须阅读的任何内容:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.MiddleName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MiddleName)
@Html.ValidationMessageFor(model => model.MiddleName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Birthdate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Birthdate)
@Html.ValidationMessageFor(model => model.Birthdate)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>}
我的问题是:如何将这些额外的装饰添加到使用 EF4 生成的实体中?除了 System.ComponentModel.DataAnnotations 之外,我还应该使用其他东西吗?我知道实体会重新生成,将其直接添加到实体的代码中可能不是一个好主意,但出于某种原因,我想不出比在 View 中手动输入标签文本更好的方法(蹩脚的,没有理由必须这样做,这就是 MVC!)。我想保留它,以便应用程序足够动态,能够为我的模型提供正确的显示信息,并保持 MVC 方法。我该怎么做?
最佳答案
我还没有为 ASP.NET MVC(仅针对 Silverlight)这样做,但我相信同样的原则也适用。您可以创建一个“元数据伙伴类”,如下所示,因为 EF 生成的类型应该是部分类型,因此您可以向它们添加更多内容(如 MetadataTypeAttribute),然后创建这个保存元数据的兄弟类。
虽然有点丑,但应该可以用。它是这样的(假设 EF 实体名为“Person”):
[MetadataType(typeof(PersonMetadata))]
public partial class Person {
// Note this class has nothing in it. It's just here to add the class-level attribute.
}
public class PersonMetadata {
// Name the field the same as EF named the property - "FirstName" for example.
// Also, the type needs to match. Basically just redeclare it.
// Note that this is a field. I think it can be a property too, but fields definitely should work.
[Required]
[Display(Name = "First Name")]
public string FirstName;
}
关于asp.net-mvc - 将 System.ComponentModel.DataAnnotations 与 Entity Framework 4.0 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4915957/