解決asp.net mvc UpdateModel更新對象後出現null問題的方法_實用技巧

來源:互聯網
上載者:User

在用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();

這樣問題就可以解決了,小編也嘗試進行了操作,結果成功了,希望也能協助這方面有困擾的童鞋解決實際問題。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.