单独文件中的元数据不会按预期显示

时间:2013-03-21 08:01:02

标签: c# asp.net-mvc-4

您好我正在尝试将我的metada添加到单独的文件中以保持我的模型像posiblen一样干净,但似乎有些错误,因为现在似乎某些属性不显示验证。这是我的模型clasS:< / p>

public partial class BookModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Author { get; set; }
    public string Description { get; set;}
    public DateTime PublicationDate { get; set; }
    public int CategoryId { get; set; }
    public decimal Price { get; set; }
    public string BookUrl { get; set; }
}

这是我的metada分类:

[MetadataType(typeof(BookModel))]
public partial class BookModelMetada
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Author { get; set; }

    [Required]
    [DataType(DataType.MultilineText)]
    public string Description { get; set; }

    [Required]
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    public DateTime PublicationDate { get; set; }

    [Required]
    public int CategoryId { get; set; }

    [Required]
    [DataType(DataType.Currency)]
    [DisplayFormat(DataFormatString = "{0:c}")]
    public decimal Price { get; set; }

    public string BookUrl { get; set; }
}

奇怪的领域是PublicationDate和Price显示验证错误,但其他属性没有。

我做错了什么?

修改

查看代码:

 <p>
            @Html.LabelFor(model => model.Book.Name, "Book Name")
            @Html.TextBoxFor(model => model.Book.Name)
        </p> 
        <p>
            @Html.LabelFor(model => model.Book.Author)
            @Html.TextBoxFor(model => model.Book.Author)
        </p>
        <p>
            @Html.LabelFor(model => model.Book.PublicationDate ,"Publication Date")
            @Html.TextBoxFor(model => model.Book.PublicationDate, new { @class="datepicker" })
        </p>
        <p>
            @Html.LabelFor(model => model.Book.Price)
            @Html.TextBoxFor(model => model.Book.Price)
        </p>
        <p>
            @Html.LabelFor(model => model.Book.CategoryId, "Select category")
            @Html.DropDownListFor(model => model.Book.CategoryId, new SelectList(Model.Categories, "Id", "Name"))
        </p>
        <p> 
            @Html.LabelFor(model => model.Book.Description)
            @Html.TextAreaFor(model => model.Book.Description)
        </p>
        <p>
            <input type="submit" value="Create" class="link"/>
            @Html.ActionLink("Back to List", "Books", "ProductManager", null, new { @class = "link" })
        </p>

2 个答案:

答案 0 :(得分:2)

问题是我在元数据类而不是模型类上添加了[MetadataType(typeof(BookModel))]

答案 1 :(得分:0)

可能有一个或多个原因: 但首先要确保在视图或视图布局中包含jquery.unobtrusive和jquery.validate。 但是您的视图似乎不清楚,您必须使用@Html.LabelFor(model =>model.Book.Author)。请发表您的完整视图。