gpt4 book ai didi

c# - 将空字符串绑定(bind)到 Guid.Empty 或避免模型状态错误

转载 作者:太空狗 更新时间:2023-10-29 22:17:27 25 4
gpt4 key购买 nike

当我为 Guid 发布一个带有空字符串“”的表单时我收到错误消息“需要 MyGuid 字段。”尽管我还没有设置“必需”属性。

//NOT Required   
public Guid MyGuid { get; set; }

绑定(bind)模型后,Guid 为 00000000-0000-0000-0000-000000000000 (因为它是默认值)这是正确的。但是 ModelState 有上述错误。

我怎样才能避免这个错误?

附加信息:

[Required(AllowEmptyStrings = true)]没有帮助

我不想让 Guid 可以为空(Guid?),因为这会导致很多额外的代码(检查它是否有值、映射等)

更新:

好的,我想通了对 Guid? 的更改在我看来,模型并没有导致比我预期的那么多的变化(一些调用 MyGuid.GetValueOrDefault() 或一些检查 MyGuid.HasValue 并调用 MyGuid.Value)。

但是,如果没有为发布请求提供有效的 Guid,则会添加模型错误的原因是 DefaultModelBinder尝试绑定(bind) nullGuid .解决方案是覆盖 DefaultModelBinder .并且不会向模型状态添加任何错误

public class MyModelBinder : DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
{
if (propertyDescriptor.PropertyType == typeof(Guid) && value == null)
{
value = Guid.Empty;
}
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);

}
}

最佳答案

如果字段的类型是 Guid(这是一个值类型),那么它必须包含一个值(即使它全为零)。具有非必需 GUID 的正确解决方案是使用 Guid? (Nullable Guid)。

您不想使用 Nullable 的理由没有道理;无论你打算用哪种方式编码“空虚”,你的代码都必须检查它。一般来说,我认为 Nullable 实际上使这更容易。

关于c# - 将空字符串绑定(bind)到 Guid.Empty 或避免模型状态错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4686590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com