解决asp.net mvc UpdateModel更新对象后出现null问题的方法
在用asp.netmvc4.0做项目的时候遇到的这种情况:
情况分析:
“在填写表单的时候,有一些表单没有填写,留空,然后直接post提交表单,action中用UpdateModel来更新model,结果发现那些没有填写的表单字段全部变成null。”
原因分析:
项目中做了判断null不能提交更新到数据库中,所以导致一直提交不上去
后来网上查了一下找到了解决办法,我在这里分享一下,方便以后遇到这种情况的朋友可以方便解决
解决方法:
新建一个类继承DefaultModelBinder
usingSystem.ComponentModel; usingSystem.Web.Mvc; namespaceCustomerWebsite.Mvc { publicsealedclassEmptyStringToNullModelBinder:DefaultModelBinder { protectedoverridevoidSetProperty(ControllerContextcontrollerContext, ModelBindingContextbindingContext,PropertyDescriptorpropertyDescriptor,objectvalue) { if(value==null&&propertyDescriptor.PropertyType==typeof(string)) { value=string.Empty; } base.SetProperty(controllerContext,bindingContext,propertyDescriptor,value); } } }
然后在Global.asax的Application_Start中替换DefaultModelBinder
ModelBinders.Binders.DefaultBinder=newEmptyStringToNullModelBinder();
这样问题就可以解决了,小编也尝试进行了操作,结果成功了,希望也能帮助这方面有困扰的童鞋解决实际问题。