MVC ModelState验证失败为null值

Chr*_*ord 2 c# validation asp.net-mvc

如果我有以下型号:

public class Model
{
    public int ModelID { get; set; }
    public string Title { get; set; }
    public DateTime Created { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

以下控制器方法:

public ActionResult Create(Model model)
{
    if (ModelState.IsValid)
    {
        model.Created = DateTime.Now;

        // Save to DB
    }
}
Run Code Online (Sandbox Code Playgroud)

在视图中隐藏Created字段,因为我希望这个字段填充调用Create控制器方法的时间戳.由于model.Created属性为null,因此无法进行ModelState验证.

我不想使model.Created属性为Nullable但我需要以某种方式指定视图中不需要此字段.有人可以建议如何做到这一点?

hai*_*770 6

您将要Created使用该[Bind]属性从绑定中排除该属性,如下所示:

public ActionResult Create([Bind(Exclude = "Created")] Model model)
{
    ....
}
Run Code Online (Sandbox Code Playgroud)

出于安全原因,也建议您使用它,因为您不希望客户Created为您设置值.