假设我有一个 form
,以及 ""
的值当 form
被选中时从 View 发送到 controller
到action method
, 将asp.net core
将空字符串转换为 NULL
值(value)?
如果我不使 [required]
的 bool 属性可以为空属性,它给了我这个错误:值 '' 无效。
这是否意味着:""
被评估为 NULL
, bool 属性不允许 NULL
, asp.net core 返回一个错误说你不能传递一个空的string
到Model
属性,因为它不可为空,因为 asp.net core
将空字符串转换为 NULL
?
最佳答案
MVC 模型绑定(bind)确实支持将空字符串绑定(bind)为空字符串或空字符串,具体取决于元数据。
您可以使用属性控制每个字段的行为;
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Property { get; set; }
或者通过实现自定义 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());
或通过提供您自己的 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());
关于c# - 在asp.net核心中,空字符串是否转换为NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60735864/