ajax post提交空字符串(string.Empty) MVC接收爲null的問題html
這個問題查了好多資料才知道緣由:ajax
if (bindingContext.ModelMetadata.ConvertEmptyStringToNull && Object.Equals(value, String.Empty)) { return null; }
當Model的元數據ConvertEmptyStringToNull爲true,而且form的值爲空字串時,返回null.json
解決方法:mvc
一、給對應的屬性加上特性ide
[DisplayFormat(ConvertEmptyStringToNull = false)]
二、覆寫模型建立元數據的方法,post
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文件中進行設置spa
ModelMetadataProviders.Current = new EmptyStringDataAnnotationsModelMetadataProvider();
參考文章:code
一、https://stackoverflow.com/questions/12734083/string-empty-converted-to-null-when-passing-json-object-to-mvc-controllerorm
二、https://www.cnblogs.com/lonelyxmas/p/5558885.htmlhtm