我有一个小应用程序,我正在创建一个客户
[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateCustomer(GWCustomer customer)
{
if (string.IsNullOrEmpty(customer.CustomerName))
{
ModelState.AddModelError("CustomerName", "The name cannot be empty");
}
//...
if (ModelState.IsValid)
{
//insert in db
}
}
我的问题是
GWCustomer
对象有一个 Id
,这是主键,不能为空。这使得验证框架将其标记为错误。但这不是错误,我还没有创建客户,现在应该是 null 直到它被保存。我该如何绕过这个?或者修复它?我永远无法将它插入数据库,因为
ModelState
永远无效。编辑 我正在使用 Linq to SQL 和存储库模式。
最佳答案
这将从绑定(bind)中排除值,但不排除验证:
public ActionResult CreateCustomer([Bind(Exclude = "Id")]GWCustomer customer)
即使发生验证,您仍然可以通过调用更正 ModelState:
ModelState.Remove("Id");
它将删除与 Id 相关的条目并更改
ModelState.Valid
如果只有 Id
,则属性为 true导致错误。不建议在 View 层中使用数据层对象。您绝对应该考虑创建专用 View 模型,而不使用
Id
field 。
关于asp.net-mvc - ASP.NET MVC - ModelState.IsValid 为假,如何绕过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2397563/