简体   繁体   中英

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.

Do I have to reset ModelState since I modified the model somehow?

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 .

By the time the line of code in your controller which sets the registration number, the ModelState validation has already occurred. It occurs prior to invoking the Create() method on your controller. 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.

The validation happens before you call IsValid , and the error will key be present in the dictionary.

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.

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)
{
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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