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.