use*_*809 3 c# asp.net data-annotations asp.net-core
假设我有一个form和值""时,选择form从视图发送到controller到action method,将asp.net core空字符串转换为NULL价值?
如果我不使该属性的布尔属性可以为空[required],则会出现以下错误:值 '' 无效。
这是否意味着:""被评估为NULL,布尔属性不允许NULL,asp.net 核心返回一个错误,说您不能将空传递string给Model属性,因为它不可为空,因为asp.net core将空字符串转换为 a NULL?
Jer*_*man 10
MVC 模型绑定确实支持将空字符串绑定为 null 或空字符串,具体取决于元数据。
您可以使用属性控制每个字段的行为;
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Property { get; set; }
Run Code Online (Sandbox Code Playgroud)
或者通过实现自定义IDisplayMetadataProvider.
public class DisplayProvider : IDisplayMetadataProvider
{
public void CreateDisplayMetadata(DisplayMetadataProviderContext context)
{
if (context.Key.ModelType == typeof(string))
context.DisplayMetadata.ConvertEmptyStringToNull = false;
}
}
// in .AddMvc(o => ...) / AddControllers(o => ...) / or an IConfigure<MvcOptions> service
[MvcOptions].ModelMetadataDetailsProviders.Add(new DisplayProvider());
Run Code Online (Sandbox Code Playgroud)
或者通过提供您自己的IModelBinder/以您喜欢的任何方式转换值IModelBinderProvider。
public class StringBindProvider : IModelBinderProvider
{
private StringBinder stringBinder = new StringBinder();
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(string))
return stringBinder;
return null;
}
}
public class StringBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value != ValueProviderResult.None)
{
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
var str = value.FirstValue?.Trim();
if (bindingContext.ModelMetadata.ConvertEmptyStringToNull && string.IsNullOrWhiteSpace(str))
str = null;
bindingContext.Result = ModelBindingResult.Success(str);
}
return Task.CompletedTask;
}
}
// see above
[MvcOptions].ModelBinderProviders.Insert(0, new StringBindProvider());
Run Code Online (Sandbox Code Playgroud)
首先你需要了解的是,这里的Options字段是 bool(not string).
The only content it can receive is true or false or null,无论输入空字符串还是true或false以外的字符串,都会被识别为null。
的属性Reuqired表示Options字段不能为null,因为Options is a bool type,所以输入空字符串后,空字符串会转为空值,并且由于reuqired属性的限制,不能为null,所以会提醒你无效。
如果要允许Options接收空值,只需要去掉reuqired属性即可。
在Required属性限制的前提下,我做了代码测试,大家可以参考:
| 归档时间: |
|
| 查看次数: |
4508 次 |
| 最近记录: |