gpt4 book ai didi

c# - MVC ModelState 验证因空值而失败

转载 作者:行者123 更新时间:2023-12-02 20:04:14 26 4
gpt4 key购买 nike

如果我有以下模型:

public class Model
{
public int ModelID { get; set; }
public string Title { get; set; }
public DateTime Created { get; set; }
}

以及以下 Controller 方法:

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

// Save to DB
}
}

在 View 中,Created 字段被隐藏,因为我希望它填充调用 Create Controller 方法时的时间戳。由于 model.Created 属性为 null,因此 ModelState 验证失败。

我不想使 model.Created 属性为 Nullable,但我需要以某种方式指定 View 中不需要此字段。有人可以建议如何实现这一目标吗?

最佳答案

您需要使用 [Bind] 属性从绑定(bind)中排除 Created 属性,如下所示:

public ActionResult Create([Bind(Exclude = "Created")] Model model)
{
....
}

出于安全原因,也建议您这样做,因为您不希望客户端为您设置 Created 值。

关于c# - MVC ModelState 验证因空值而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19362287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com