Home Asp NetCore 2 Required validation - ModelState Valid is true when in error
Reply: 2

Asp NetCore 2 Required validation - ModelState Valid is true when in error

apj1981
1#
apj1981 Published in 2017-12-07 20:46:52Z

I'm trying to get some required field validation working in AspNetCore 2, and what I expect to happen, isn't happening.

Model

[Required(ErrorMessage = "The game name cannot be blank")]
[StringLength(100,ErrorMessage = "The game name must be between 2 and 100 characters", MinimumLength = 2)]
[Display(Name = "Name")]
public string GameName { get; set; }

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult GameDetail(GameDetail model, IFormCollection form)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    // code removed for clarity
}

View

<div asp-validation-summary="ModelOnly" class="text-danger"></div>

<form class="form" method="post">
  <div class="form-group">
    <label class="form-label" asp-for="GameName"></label>
    <span asp-validation-for="GameName" class="text-danger"></span>
    <input class="form-control" asp-for="GameName" class="form-control" />
  </div>
  <div class="form-group">
    <input class="button" type="submit" value="Continue">
  </div>
</form>

In MVC5, if this form was posted with no value entered, ModelState would be invalid and an error would be returned to the view.

However, in this instance, ModelState.IsValid is true, but the error count is 1 and the error list does show the field is required as an error.

I have tried a few things including adding [Bind("GameName")] on the post parameters against the model and also [BindRequired] on the model as well as this post: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation

Yet, the form submits and redirects to the next page (code removed for clarity) without showing any errors.

I would expect to see the view returned with the field error message showing the required error message and an error summary showing the same error.

Tony Basallo
2#
Tony Basallo Reply to 2017-12-07 21:01:31Z

I think you have to add AllowEmptyString=false on the required attribute.

[Required (AllowEmptyStrings = false)]
apj1981
3#
apj1981 Reply to 2017-12-07 22:46:46Z

Goddamnit! Right, it was a complete and utter screw up on my part and I don't know why I didn't see this first! I coded the page with a simple form first just to get a layout sorted, so just used IFormCollection to save me writing a model

public IActionResult GameDetail(GameDetail model, IFormCollection form)

Removed the IFormCollection form and it works exactly as I expect it to.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301071 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO