c# - 使用元数据类覆盖 MVC View 模型中的 EF 字段名称不起作用

标签 c# asp.net-mvc entity-framework asp.net-mvc-5

我正在编写一个 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/

相关文章:

c# - 如何在 ASP.NET MVC Url.Action 中使用 C# nameof()

entity-framework - 解决WCF数据服务问题上的DateTimeOffset的最佳方法

c# - 以编程方式启用 Windows 功能的最佳方法是什么?

asp.net-mvc - 您可以只更新部分 View 而不是整页帖子吗?

asp.net-mvc - 如何在 ASP.NET MVC 中将数据从子操作传递到布局

c# - 调用数据访问层的通用方法

c# - Entity Framework ISNULL 在 Where 条件

c# - 锁和互斥锁有什么区别?

c# - Split() 方法的解释

c# - 当用户无权复制文件时使用 UAC 提示