Mike de Klerk Mike de Klerk - 1 month ago 6
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
@Html.ValidationMessage("InvoiceNr")
is added to the cshtml file. Only
asp-validation-for="InvoiceNr"
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.

Thanks!

@Shyju

<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" />
</div>
</div>


@GSerg
enter image description here

Answer

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.

Replace

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

With

<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.

Comments