.net mvc中用AJAX请求后台方法时,空字符传会自动转为null
解决方案:重写DataAnnotationsModelMetadataProvider方法中的CreateMetadata方法
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web.Mvc; namespace Web { public class MyDataAnnotationsModelMetadataProvider : DataAnnotationsModelMetadataProvider { protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) { var md = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); DataTypeAttribute dataTypeAttribute = attributes.OfType<DataTypeAttribute>().FirstOrDefault(); DisplayFormatAttribute displayFormatAttribute = attributes.OfType<DisplayFormatAttribute>().FirstOrDefault(); if (displayFormatAttribute == null && dataTypeAttribute != null) { displayFormatAttribute = dataTypeAttribute.DisplayFormat; } if (displayFormatAttribute == null) { md.ConvertEmptyStringToNull = false; } return md; } } }
//在Global.asax的Application_Start方法中,重新覆盖原有对象
ModelMetadataProviders.Current = new MyDataAnnotationsModelMetadataProvider();