Asp.net MVC3 DropdownList验证

时间:2012-07-09 08:08:58

标签: asp.net-mvc-3 validation html-select

型号:

public class Product
{
    public string Title { get; set; }

    [Required]
    public int CategoryId { get; set; } 
    //or
    public int? CategoryId { get; set; } 
}

控制器:

ViewBag.Categories = db.Categories.ToList();

查看:

@Html.DropDownListFor(m => m.CategoryId , new SelectList(ViewBag.Categories , "CategoryId ", "Title"),"")
@Html.ValidationMessageFor(model => model.CategoryId )

我有客户端验证

但是在Microsoft Default Scaffolding:

控制器:

ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId ", "Title");

查看:

@Html.DropDownList("CategoryId" ,"")

这是非常好和干净的代码。但客户端验证不起作用。我如何使用Microsoft默认的脚手架语法,我有客户端验证

1 个答案:

答案 0 :(得分:0)

让你的CategoryId属性可以为空

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