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
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.
Alternatives to built-in attributes If you need validation not provided by built-in attributes, you can: Create custom attributes. Implement IValidatableObject.
I suggest try changing this:
<span asp-validation-for="FirstName" />
like this:
<span asp-validation-for="FirstName"></span>
maybe it will make a difference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With