欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解決asp.net mvc UpdateModel更新對(duì)象后出現(xiàn)null問題的方法

 更新時(shí)間:2015年11月05日 15:50:05   投稿:lijiao  
這篇文章主要介紹了解決asp.net mvc UpdateModel 更新對(duì)象后出現(xiàn)null問題的方法,需要的朋友可以參考下

在用asp.net mvc 4.0做項(xiàng)目的時(shí)候遇到的這種情況:
情況分析:
“在填寫表單的時(shí)候,有一些表單沒有填寫,留空,然后直接post 提交表單,action中用UpdateModel 來更新model,結(jié)果發(fā)現(xiàn)那些沒有填寫的表單字段全部變成null?!?br /> 原因分析:
項(xiàng)目中做了判斷null不能提交更新到數(shù)據(jù)庫中,所以導(dǎo)致一直提交不上去
后來網(wǎng)上查了一下找到了解決辦法,我在這里分享一下,方便以后遇到這種情況的朋友可以方便解決
解決方法:
新建一個(gè)類繼承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();

這樣問題就可以解決了,小編也嘗試進(jìn)行了操作,結(jié)果成功了,希望也能幫助這方面有困擾的童鞋解決實(shí)際問題。

相關(guān)文章

最新評(píng)論