我正在编写一个 MVC5/EF6 网站,我正在尝试尽可能完整地分离数据模型和 View 模型。
所以我的 EF 类(存储在单独的程序集中)如下所示:
public class WorksOrder
{
[Key]
public int Id { get; set; }
public string CreatedById { get; set; }
}
我的 View 程序集( View Controller 所在的位置)中有一个元数据类,我在其中覆盖了显示名称并添加了错误消息
public class WorksOrder
{
[Display(Name = "Created by")]
[Required(ErrorMessage = "created by cannot be blank")]
public string CreatedById { get; set; }
}
我在我的 View 模型中附加了两个类:
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(typeof(EF.Models.WorksOrder),
typeof(ViewMetadata.WorksOrder)), typeof(EF.Models.WorksOrder));
当我显示表单时,字段标签是“CreatedById”,而不是元数据类中指定的显示属性(“创建者”)。我知道 AddProviderTransparent 有效,因为如果我尝试提交 CreatedById 字段为空的表单,我会收到错误消息(“创建者不能为空”)。
编辑:这是 Razor 文件(我已经清除了不重要的东西(divs 等)。
@model App.Models.WorksOrderCreateModel
@using (Html.BeginForm())
{
@Html.LabelFor(model => model.WorksOrder.CreatedById, new { @class = "control-label col-md-3" })
@Html.TextBoxFor(model => model.WorksOrder.CreatedById, new { @class = "form-control col-md-3" })
@Html.ValidationMessageFor(model => model.WorksOrder.CreatedById)
最佳答案
在 MetaData 类中创建一个像这样的部分类。
[MetadataType(typeof(WorksOrderMetaData))]
public partial class WorksOrder
{
}
public class WorksOrderMetaData
{
[Display(Name = "Created by")]
[Required(ErrorMessage = "created by cannot be blank")]
public string CreatedById { get; set; }
}
这会起作用
关于c# - 使用元数据类覆盖 MVC View 模型中的 EF 字段名称不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21904022/