asp-validation-for tag helper is not working for server side validation errors
Asked Answered
N

1

9

CustomerEntryModel

    [Required]
    public String FirstName { get; set; }

CustomerController.cs

    [HttpGet]
    [Route("Get")]
    public IActionResult Get()
    {
        CustomerEntryModel model = new CustomerEntryModel();
        return View("CustomerEntry", model);
    }

    [HttpPost]
    [Route("Update")]
    public ActionResult Update([FromForm]CustomerEntryModel model)
    {
        if (!ModelState.IsValid)
        {
            return View("CustomerEntry", model);
        }
        return null;
    }

CustomerEntry.cshtml

@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
<form asp-controller="Customer" asp-action="Update" method="post">
    <input type="text" asp-for="FirstName" />
    <span asp-validation-for="FirstName" />
    <input type="submit" value="Submit" />
</form>

I do not include the jQuery validation libraries, so the validation occurs on the server side. Now, when I submit the page with first name empty, the update action gets executed and I receive back the same view, but without any error.

Instead of <span asp-validation-for="FirstName" /> tag helper, if I use the html helper @Html.ValidationMessageFor(m => m.FirstName) I get the required error for first name.

As per my understanding TagHelper extends the behavior of traditional HtmlHelper to provide HTML friendly development experience. That means, something that works with HtmlHelper has to work with it's TagHelper counterpart.

After the ModelState.IsValid call, I CAN see Controller.ModelState (instance of ModelStateDictionary), having the error for FirstName property. However, the TagHelper isn't able to bind it.

You can find the MVC6 validation tag helpers detail here,

http://www.davepaquette.com/archive/2015/05/14/mvc6-validation-tag-helpers-deep-dive.aspx

Nellenelli answered 13/9, 2016 at 7:17 Comment(1)
This is a registered issue in the framework github.com/aspnet/Mvc/issues/4475Oersted
A
30

I suggest try changing this:

<span asp-validation-for="FirstName" />

like this:

<span asp-validation-for="FirstName"></span>

maybe it will make a difference

Adjure answered 13/9, 2016 at 13:15 Comment(5)
I am having the same problem as the OP and this does not work.Menjivar
Yes, surprisingly the self-closing tag causes the problem.Narayan
best answer of the day ;)Marriage
It is amazing that this fixed it for me. What's the difference?Myrta
The issue still exists even in 2024, with asp.net core 8.Dessiedessma

© 2022 - 2024 — McMap. All rights reserved.