asp.net core中,空字符串是否转换为NULL?

In asp.net core, are empty string converted to NULL?

假设我有一个 form,当 form 从视图发送到 controller 再到 [=15] 时选择了 "" 的值=], asp.net core 会将空字符串转换为 NULL 值吗?

如果我不让 [required] 属性的布尔值 属性 可以为空,它会给我这个错误:值 '' 无效。

这是否意味着:""被评估为NULL,布尔属性不允许NULL,asp.net核心returns 一个错误,指出您不能将空 string 传递给 Model 属性 因为它不可为空,因为 asp.net core 将空字符串转换为 NULL

不,它们不是 - 消息说 "The value '' is invalid." 这就是空字符串的样子。

如果您不想设置必填字段,则需要为 boolean 设置值。如果为空则需要发送false

MVC 模型绑定确实支持将空字符串绑定为 null 或空字符串,具体取决于元数据。

您可以使用属性控制每个字段的行为;

[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());

首先要明白的是这里的Options字段是bool(not string)的类型。

The only content it can receive is true or false or null,无论输入空串还是非真假串,都会被识别为null。

Reuqired的属性表示Options字段不能为null,因为Options is a bool type,所以输入空字符串后,空字符串会被转为null值,由于reuqired属性的限制,不能为null,所以会提示invalid。

如果想让Options接收空值,只需要去掉reuqired属性即可。

在Required属性限制的前提下,我做了代码测试,可以参考: