I'm used to the ASP.NET Webforms easy way of doing AJAX with UpdatePanels. I understand the process is much more artisanal with MVC.
In a specific case, I'm using Data Annotations to validate some form inputs. I use the HTML.ValidationMessageFor helper to show an error message. If I want to use AJAX to post this form and show this error message, what would be the process? Is it possible to keep the HTML.ValidationMessageFor and make it work with AJAX?
Thank you.
This article might be helpful: ScottGu's blog: ASP.NET MVC 2: Model Validation.
The validation used in MVC can be both client and server side. To enable client-side validation use the:
declaration somewhere in your view. This negates the need to use AJAX to post your form to the server and then display the results inline, as users with javascript enabled will have their own clientside validation.
Are you using the built-in AJAX methods? For example, are you created the AJAX form with
Ajax.BeginForm(...)
? If so, it's very easy to show validation messages.One more thing: do you want to display a validation message for each individual incorrect control, or do you just want to have a validation summary above your form? I'm pretty sure you're asking about displaying an individual message for each control, but I'll include both just in case.
To display an individual message for each incorrect control:
First, you need to put your form inputs inside a Partial View. I'll call that Partial View
RegisterForm.ascx
.Next, you should have something like this in your view:
Finally, your Controller Action should look something like this:
To display only a validation summary above your form:
You should first create a separate ValidationSummary Partial View. Here's what the code of
ValidationSummary.ascx
should look like:Next, inside your view, you should have something like this:
Finally, your Controller Action should resemble this:
Hope that helps!