错误为可空INT分配空 - "值'空'是无效的财产" [英] Error assigning null to a nullable int - "The value 'null' is not valid for property"

查看:265
本文介绍了错误为可空INT分配空 - "值'空'是无效的财产"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个属性在我的视图模型:

I have this property in my view model:

[DisplayName("Region")]
public int? RegionId { get; set; }

我通过我的视图模型为我的控制器,并在 ModelState.IsValid 失败,如果RegionId为null。如果我传递给它一个整数,它工作正常。

I pass my view model to my controller, and it fails at ModelState.IsValid if RegionId is null. If I pass an integer to it, it works fine.

错误消息是:

'空'的值不是有​​效的区域

The value 'null' is not valid for Region

我也试过在调用此我检查之前 ModelState.IsValid ,但我得到了同样的错误:

I've also tried calling this before I check ModelState.IsValid, but I get the same error:

if (viewModel.RegionId == null)
    viewModel.RegionId = (int?)null;

这里有什么问题吗?为什么我不能指定空的东西,可为空?

What's the problem here? Why can't I assign null to something that is nullable?

推荐答案

在你的Global.asax.cs文件,在Application_Start方法中,添加以下行:

In your Global.asax.cs file, in the Application_Start method, add the following line:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

问题是,即使是空值类型,默认情况下,一个必需的属性由默认ValidatorProvider补充说。

The issue is that, even for a nullable value type, by default, a "Required" attribute is added by the default ValidatorProvider.

这篇关于错误为可空INT分配空 - "值'空'是无效的财产"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆