find UpdateModel Fail Reason

2019-06-05 08:41发布

问题:

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; } 

回答1:

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
  });


回答2:

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

}