实体上的DataAnnotations未在View中显示

时间:2012-06-14 16:40:21

标签: asp.net-mvc-3

我有一个包含

的供应商权利
ID - int
Status - string
Name - string
CreateDate- datetime

我正在使用partial class方法为上面的Entity.as here

创建数据注释
namespace TemplateEx.Models
{
    [MetadataType(typeof(SupplierMetadata))]
    public partial class Supplier
    {
        // Note this class has nothing in it.  It's just here to add the class-level attribute.
    }

    public class SupplierMetadata
    {
        // 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 = "Supplier Name")]
        public string Name;
    }
}

我定义了一个控制器动作,如下所示

 public ViewResult Details(int id)
    {
        Supplier supplier = db.Suppliers1.Single(s => s.ID == id);
        return View(supplier);
    }

当我为此操作创建视图并选择了供应商实体的详细信息脚手架以下是我作为视图获取的内容

@model TemplateEx.Models.Supplier

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<fieldset>
    <legend>Supplier</legend>

    <div class="display-label">CreateDate</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.CreateDate)
    </div>

    <div class="display-label">Status</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Status)
    </div>

    <div class="display-label">Name</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Name)
    </div>
</fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { id=Model.ID }) |
    @Html.ActionLink("Back to List", "Index")
</p>

注意model.Name如何有一个“Name”标签而不是“Supplier Name”。我做错了什么?

1 个答案:

答案 0 :(得分:3)

替换

<div class="display-label">Name</div>

<div class="display-label">@Html.LabelFor(model => model.Name)</div>

编辑:

关于第二个问题,请看这里 How can i enforce the scaffolding automatically generated code to display the Label and the EditorFor text field at the same line in my asp.net mvc 3(特别是最后一个答案)