Для предотвращения ASP.NET MVC от получения null
для string
свойств, мы можем добавить аннотацию к string
свойствам:Как добавить свойство аннотации глобально
[DisplayFormat(ConvertEmptyStringToNull = false)]
Что я ищу, чтобы это глобально (в целом проекте). Итак, я попытался создать пользовательскую модель связующего:
public class NotNullStringModelBinder : DefaultModelBinder {
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
if(controllerContext == null)
throw new ArgumentNullException("controllerContext");
if(bindingContext == null)
throw new ArgumentNullException("bindingContext");
var providerResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if(providerResult == null)
return string.Empty;
var attemptedValue = providerResult.AttemptedValue;
return attemptedValue ?? string.Empty;
}
}
я добавил это в (global.asax).Application_Start()
:
ModelBinders.Binders.Add(typeof(string), new NotNullStringModelBinder());
Но это не работает, и я получаю null
для пустых строк во всех моделях , Что я пропустил? Любая идея, пожалуйста?
возможно дубликат http://stackoverflow.com/questions/7490210/asp-net-mvc-3-bind-string-property-as-string-empty-instead-of -null – Kell