find UpdateModel Fail Reason

2019-06-05 08:50发布

In a create view page, all jquery validation pass, when the create object got passed into action, the UpdateModel fails. Is there anyway that I can find which field explicitly fail the update? By watching "e" in Debug Mode?

 try { 
      UpdateModel(house_info); }
 catch (Exception e) 
     { throw e; } 

2条回答
放荡不羁爱自由
2楼-- · 2019-06-05 09:04

You can inspect ModelState for errors. The following will give you the list of each property that has an error and the first error associated with the property

var errors = ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0)
  .Select(k => new
  {
    propertyName = k,
    errorMessage = ModelState[k].Errors[0].ErrorMessage
  });
查看更多
做个烂人
3楼-- · 2019-06-05 09:12

Additionally, the ModelState has a .IsValid property which you should probably be checking rather than using exception handling.

A controller action would perhaps look like:

public void MyAction() {

    if(ModelState.IsValid) {
        // do things
    } 

    // error handling, perhaps look over the ModelState Errors collection
    // or return the same view with the 'Model' as a parameter so that the unobtrusive javascript
    // validation would show the errors on a form

}
查看更多
登录 后发表回答