C# 希望能够接收空字符串而不是空字符串
我有一个带有string属性的mvc模型,当我接收到json参数,并且在客户端上设置为空字符串时,我接收到字符串参数的null I mvc控制器操作 我希望能够接收空字符串而不是空字符串,并尝试了以下操作:C# 希望能够接收空字符串而不是空字符串,c#,asp.net-mvc,C#,Asp.net Mvc,我有一个带有string属性的mvc模型,当我接收到json参数,并且在客户端上设置为空字符串时,我接收到字符串参数的null I mvc控制器操作 我希望能够接收空字符串而不是空字符串,并尝试了以下操作: [MetadataType(typeof(TestClassMetaData))] public partial class TestClass { } public class TestClassMetaData { private string _note; [St
[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 ?? ""; }
}
}
使用此选项将生成验证错误
有人知道它为什么不起作用吗
还有,为什么元数据类使用对象作为属性类型?添加属性:
[Required(AllowEmptyStrings = true)]
对于
的属性定义,请注意
(实际上应该是字符串类型
)。默认情况下DefaultModelBinder
使用convertEmptyStringToFull
的默认值,即true
如果要更改此行为,应使用DisplayFormat
属性,并将字符串属性的属性convertEmptyStringToFull
设置为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());
}
}
我希望这个代码能起作用