1
votes

I'm having problems understanding how to best implement unobtrusive client side validation that works together with errors added in the controller with ModelState.AddModelError().

So, this is the current code:

@Html.ValidationSummary(true)
@Html.ValidationMessageFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.LastName)

The error message will correctly appear if I'm leaving out firstname. If I enter a firstname and tab out, the message will disappear - as it should work.

When no client error exists and I can submit this form, I have to do a check against the database that the user doesn't already exists. If it does, I'm adding an error with:

ModelState.AddModelError("", "User already exists")

When returning the model, an error box is shown, but there is no message in there.

If i change @Html.ValidationSummary(true) to @Html.ValidationSummary(false) I will see the error message correctly returned with the model. (Edit: Jan's comment solved this part)

The problem now is, that all client validation will be duplicated and shown in two different places.

Also, I would like the errors to show up in the same place/div. As it is now, it will be two different validation summaries.

Any way around this?

1
This should work (empty string as key parameter to AddModelError and ValSum(true)). Are you surem you pass an empty string as key parameter?Jan
Thanks! I hadn't compiled after setting it to empty. Now it displays the error message correctly. I still have the problem that there is two error boxes now: One for the summary with the modelstate error and then one for the client errors that are predefined with: @Html.ValidationMessageFor()Andreas

1 Answers

0
votes

The validation you have set next to your text boxes you can set the text of the @Html.ValidationMessageFor(model => model.LastName) to @Html.ValidationMessageFor(model => model.LastName, ""). Or if you wanted to add a '*' if you wanted. Then you would not have the message next to your textbox.