ajax post提交空字符串(string.Empty) MVC接收为null的问题
ajax post提交空字符串(string.Empty) MVC接收为null的问题
这个问题查了好多资料才知道原因:
if (bindingContext.ModelMetadata.ConvertEmptyStringToNull && Object.Equals(value, String.Empty)) { return null; }
当Model的元数据ConvertEmptyStringToNull为true,并且form的值为空字串时,返回null.
解决方法:
1、给对应的属性加上特性
[DisplayFormat(ConvertEmptyStringToNull = false)]
2、覆写模型创建元数据的方法,
public class EmptyStringDataAnnotationsModelMetadataProvider : DataAnnotationsModelMetadataProvider { protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) { var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); modelMetadata.ConvertEmptyStringToNull = false; return modelMetadata; } }
并在Global.asax文件中进行设置
ModelMetadataProviders.Current = new EmptyStringDataAnnotationsModelMetadataProvider();
参考文章:
1、https://stackoverflow.com/questions/12734083/string-empty-converted-to-null-when-passing-json-object-to-mvc-controller
2、https://www.cnblogs.com/lonelyxmas/p/5558885.html