简体   繁体   English

为什么在 ModelState.IsValid 检查之前更新模型时 ModelState 会报错?

[英]Why does ModelState report errors when I update the model before the ModelState.IsValid check?

My controller code looks like:我的控制器代码如下所示:

[HttpPost]
public ActionResult Create(ExampleViewModel model)
{
    model.User.RegistrationNumber = this.RegistrationNumber;

    if (ModelState.IsValid)
    {

    }

    return View("Create", model);
}

I keep getting a validation error message saying that "Registration Number cannot be blank" yet I am setting it explicitly.我不断收到一条验证错误消息,指出"Registration Number cannot be blank"但我正在明确设置它。

Do I have to reset ModelState since I modified the model somehow?由于我以某种方式修改了模型,我是否必须重置ModelState

What happenned basically I set the textbox to disabled, and then during the form post the data was lost so I have to explicitly set it again.发生的事情基本上是我将文本框设置为禁用,然后在表单发布期间数据丢失了,所以我必须再次明确设置它。

Because you set the text box to disabled, the data wasn't posted.由于您将文本框设置为禁用,因此未发布数据。

As you're setting the value yourself, you can just remove the errors on that field by doing the following:当您自己设置值时,您可以通过执行以下操作来删除该字段上的错误:

ModelState.Remove("User.RegistrationNumber");

before calling ModelState.IsValid .调用ModelState.IsValid之前

By the time the line of code in your controller which sets the registration number, the ModelState validation has already occurred.到控制器中设置注册号的代码行时,ModelState 验证已经发生。 It occurs prior to invoking the Create() method on your controller.它发生在调用控制器上的 Create() 方法之前。 It's hard to know from your description what exactly you are trying to achieve, but if you don't want that field validated you could turn off validation for that field by commenting out the [required] attribute.很难从您的描述中知道您究竟想要实现什么,但是如果您不想验证该字段,您可以通过注释掉 [required] 属性来关闭对该字段的验证。

The validation happens before you call IsValid , and the error will key be present in the dictionary.验证发生在您调用IsValid之前,错误将出现在字典中。

I'm not sure if this is the best way to handle it, but I've been doing something like this:我不确定这是否是处理它的最佳方式,但我一直在做这样的事情:

[HttpPost]
public ActionResult Create(ExampleViewModel model)
{
    if (ModelState["User.RegistrationNumber"].Errors.Count == 1) {
        model.User.RegistrationNumber = this.RegistrationNumber;
        ModelState["User.RegistrationNumber"].Errors.Clear();
    }
}

The other solutions here didn't work as expected in .NET Core 3.1 so I used the following alternative, which explicitly sets the Validation state of only the desired model property.此处的其他解决方案在 .NET Core 3.1 中没有按预期工作,因此我使用了以下替代方案,它仅显式设置所需模型属性的验证状态。

if (ModelState["Property"].Errors.Count > 0)
{
    model.Property = someRequiredProperty; // db query using FirstOrDefault()

    if (model.Property != null)
    {
        ModelState["Property"].ValidationState = ModelValidationState.Valid;
    }
}

if (ModelState.IsValid)
{
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM