Method to solve null problem after asp. net mvc UpdateModel updates object

  • 2021-07-06 10:44:31
  • OfStack

This is the case when you are working on a project with asp. net mvc 4.0:
Situation analysis:
"When filling out the form, some forms were not filled out and left blank, and then the form was submitted directly by post. UpdateModel was used to update model in action, and it was found that all the form fields that were not filled out became null."
Cause analysis:
In the project, it was judged that null could not submit updates to the database, so 1 could not be submitted directly
Later, I found a solution after checking it on the Internet. I share it here. It is convenient for friends who encounter this situation in the future to solve it conveniently
Solution:
Create a new class to inherit 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);
  }
 }
}

Then replace DefaultModelBinder in Application_Start of Global. asax


ModelBinders.Binders.DefaultBinder = new EmptyStringToNullModelBinder();

This problem can be solved, this site has also tried to operate, the results are successful, I hope to help this area has trouble children shoes to solve practical problems.


Related articles: