Имея форму со входом:
<input name="MyProperty" />
Его соответствующая модель / свойство:
public class MyModel
{
public string MyProperty { get; set; }
}
Мне нужно связать пустую строку вместо нуля в MyProperty
, когдаЯ отправляю форму.
Я пробовал ее с CustomBinder, который наследуется от: DefaultModelBinder
public class MyCustomBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name == "MyProperty")
{
var valueToBind = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
if(valueToBind != null && valueToBind.AttemptedValue == null)
{
propertyDescriptor.SetValue(bindingContext.Model, "");
return;
}
else
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
return;
}
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
Но valueToBind.AttemptedValue вместо null, он поставляется с заполнителем в виде текста,Но в контроллере это значение равно нулю.
Мне нужно преобразовать значение MyProperty
в пустую строку, если оно равно нулю.