解决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();
这样问题就可以解决了,小编也尝试进行了操作,结果成功了,希望也能帮助这方面有困扰的童鞋解决实际问题。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下