To solve the null problem after asp.net mvc UpdateModel updates the object, mvcupdatemodel

Source: Internet
Author: User

To solve the null problem after asp.net mvc UpdateModel updates the object, mvcupdatemodel

This situation occurs when asp.net mvc 4.0 is used for a project:
Situation analysis:
"When filling out the form, some forms are left blank, and then submitted directly by post. The model is updated using UpdateModel in the action. The results show that all the unfilled form fields are changed to null."
Cause analysis:
If null is determined in the project, it cannot be submitted and updated to the database. As a result, it cannot be submitted all the time.
Later, I found a solution on the Internet. I will share it here to help you solve this problem in the future.
Solution:
Create a class to inherit the defamodelmodelbinder

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);  } }}

Replace defamodelmodelbinder in Application_Start of Global. asax.

ModelBinders.Binders.DefaultBinder = new EmptyStringToNullModelBinder();

In this way, the problem can be solved. The small Editor also tried the operation and the result was successful. I hope that the problem can be solved by the children's shoes.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.