1

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

Mike de Klerk
  • 11,906
  • 8
  • 54
  • 76
  • 1
    Can you share how you tried `asp-validation-for` in the view ? – Shyju Nov 04 '16 at 17:02
  • Possible duplicate of [Tag Helpers - Self closing HTML tags is a bad habit?](http://stackoverflow.com/questions/39486703/tag-helpers-self-closing-html-tags-is-a-bad-habit) – GSerg Nov 04 '16 at 19:33

1 Answers1

4

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 not need to use both the tag helper and the html helper together to the the validation error. With the correct usage of tag helper, you will be able to see the validation error message.

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • 1
    Thats it indeed. That baffles me. The scaffolding does not seem to have produced a very useful template in my opinion. Thanks so much for the very quick help! – Mike de Klerk Nov 04 '16 at 17:17
  • @MikedeKlerk If that is indeed what scaffolding produces, it must be reported as a bug (see http://stackoverflow.com/q/3558119/11683). – GSerg Nov 04 '16 at 19:28