find UpdateModel Fail Reason

折月煮酒 提交于 2020-01-03 03:04:16

问题


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

}


来源:https://stackoverflow.com/questions/25842873/find-updatemodel-fail-reason

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!