Mike de Klerk Mike de Klerk - 1 year ago 70
C# Question

Why are both asp-validation-for and @Html.ValidationMessage() required?

I'm checking out Asp.Net Core on .Net core. Scaffolding has created some templates. The default validation for the model is not sufficient, so I've added some extra validation when the object is send to the controller

ViewData.ModelState.AddModelError(nameof(Invoice.InvoiceNr), "Invoice number should be unique.");

Now in the browser I only see that message when
is added to the cshtml file. Only
does not seem to present any property errors.

It took some time before I figured this out. Can someone shed some light on this why this is, it seems counter-intuitive to me, to have to add 2 lines to show all validation errors.



<div class="form-group">
<label asp-for="InvoiceNr" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="InvoiceNr" class="form-control"/>
<span asp-validation-for="InvoiceNr" class="text-danger" />

enter image description here

Answer Source

The reason it is not working is because you are not using the validation-for tag helper correctly. Instead of using the self closing notation, you should use an explicit closing for the span.


<span asp-validation-for="InvoiceNr" class="text-danger" />


<span asp-validation-for="InvoiceNr" class="text-danger"></span>

In short, you do need to use both the tag helper and the html helper. With the correct usage of tag helper, you will be able to see the validation error message.