Bri*_*ard 7 validation asp.net-mvc
我有一个小应用程序,我在创建一个客户
[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
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是该GWCustomer对象有一个Id,它是主键,不能为null.这使得验证框架将其标记为错误.但这不是一个错误,我还没有创建客户,现在应该是null,直到它被保存.我该如何绕过这个?还是解决它?
我永远不会把它插入数据库,因为ModelState它永远不会有效.
编辑我正在使用Linq to SQL和存储库模式.
Luk*_*Led 28
这将从绑定中排除值,但不会验证:
public ActionResult CreateCustomer([Bind(Exclude = "Id")]GWCustomer customer)
Run Code Online (Sandbox Code Playgroud)
即使发生验证,您仍然可以通过调用以下方法来更正ModelState:
ModelState.Remove("Id");
Run Code Online (Sandbox Code Playgroud)
ModelState.Valid如果仅Id导致错误,它将删除与Id相关的条目并将属性更改为true .
建议不要在视图层中使用数据层对象.你应该考虑创建专用的视图模型,没有Id字段.
| 归档时间: |
|
| 查看次数: |
11297 次 |
| 最近记录: |