Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 954
Mukesh Bhojwani Avatar asked Sep 13 '16 07:09

Mukesh Bhojwani


People also ask

What is ASP for tag helper?

This Tag Helpers populate <select> tag of HTML and also associated option elements for the properties of the error. The asp-for attribute of this tag helps is used to mention the model property name of the select element. Similarly, asp-items specify the option element.

Which of the following are alternatives to perform model validation instead of using built-in validation attributes?

Alternatives to built-in attributes If you need validation not provided by built-in attributes, you can: Create custom attributes. Implement IValidatableObject.


1 Answers

I suggest try changing this:

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

like this:

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

maybe it will make a difference

like image 57
Joe Audette Avatar answered Nov 11 '22 01:11

Joe Audette