解决asp.net mvc UpdateModel更新对象后出现null问题的方法

 更新时间:2021年9月22日 10:09  点击:1982

在用asp.net mvc 4.0做项目的时候遇到的这种情况:
情况分析:
“在填写表单的时候,有一些表单没有填写,留空,然后直接post 提交表单,action中用UpdateModel 来更新model,结果发现那些没有填写的表单字段全部变成null。”
原因分析:
项目中做了判断null不能提交更新到数据库中,所以导致一直提交不上去
后来网上查了一下找到了解决办法,我在这里分享一下,方便以后遇到这种情况的朋友可以方便解决
解决方法:
新建一个类继承DefaultModelBinder

using System.ComponentModel;
using System.Web.Mvc;
namespace CustomerWebsite.Mvc
{
 public sealed class EmptyStringToNullModelBinder : DefaultModelBinder
 {
  protected override void SetProperty(ControllerContext controllerContext,
   ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
  {
   if (value == null && propertyDescriptor.PropertyType == typeof(string))
   {
    value = string.Empty;
   }

   base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
  }
 }
}

然后在Global.asax的Application_Start中替换DefaultModelBinder

ModelBinders.Binders.DefaultBinder = new EmptyStringToNullModelBinder();

这样问题就可以解决了,小编也尝试进行了操作,结果成功了,希望也能帮助这方面有困扰的童鞋解决实际问题。

[!--infotagslink--]

相关文章