希望能够接收空字符串而不是null

时间:2013-10-19 14:53:38

标签: c# asp.net-mvc

我有一个带字符串属性的mvc模型,当我收到json参数时,在客户端设置为空字符串我收到null i mvc控制器操作为字符串参数。

我希望能够收到一个空字符串而不是null,并尝试了以下内容:

[MetadataType(typeof(TestClassMetaData))]
public partial class TestClass
{
}

public class TestClassMetaData
{
     private string _note;

    [StringLength(50, ErrorMessage = "Max 50 characters")]
    [DataType(DataType.MultilineText)]
    public object Note
    {
        get { return _note; }
        set { _note = (string)value ?? ""; }
    }

}

使用它会产生验证错误。

有人知道它为什么不起作用吗?

为什么元数据类使用属性类型的对象?

2 个答案:

答案 0 :(得分:1)

添加属性:

[Required(AllowEmptyStrings = true)]

Note的属性定义(应该是string类型的。)

答案 1 :(得分:1)

默认情况下,DefaultModelBinder使用默认值ConvertEmptyStringToNull,即true

我想要更改此行为,您应该使用DisplayFormat属性并将属性ConvertEmptyStringToNull设置为false以获取字符串属性。

public class YourModel
{
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public string StringProperty { get; set; }

    //...
}

我没有检查填充解决方案,但您可以尝试并为项目中的所有字符串属性实现自定义模型绑定器。

public class CustomStringBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;
        return base.BindModel(controllerContext, bindingContext);
    }
}

实现自定义字符串绑定后,您应该在Global.asax.cs

中注册它
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        ModelBinders.Binders.Add(typeof(string), new StringBinder());
    }
}

我希望这段代码有效。