ASP.NET MVC 2 server-side validation for ajax form
I've faced the following problem. I'm developing a form for the site and this form should have validation. I wanna to use native 开发者_JAVA技巧ASP.NET MVC 2 validation functionality but get stubborn with it. I have a form that is loaded via $.get and displayed using jQuery UI modal dialog. All examples I found explains how to use MVC validation with simple forms and avoid Ajax forms.
I can enable client side validation for this form, but I need to handle server-side validation correctly. How can I handle server-side validation model errors for ajax forms?
When you pass your object back to the controller, you have to wrap your code in If ModelState.IsValid
Below is a simplified version of how I edit a user. The first "EDIT" sends the User object TO the View. The second "EDIT" handles the post from the view.
Function Edit() As ActionResult
''# do stuff to populate your User
Return View(User)
End Function
<AcceptVerbs(HttpVerbs.Post)> _
Function Edit(ByVal user as User)
If ModelState.IsValid Then
''# do your valid stuff
Else
''# The posted form was not valid, send the user back
Return View(user)
End If
End Function
Here's the same thing in C#
public ActionResult Edit()
{
// do stuff to populate your User
return View(User);
}
[AcceptVerbs(HttpVerbs.Post)]
public object Edit(User user)
{
if (ModelState.IsValid) {
// do your valid stuff
} else {
//'# The posted form was not valid, send the user back
return View(user);
}
}
EDIT:
On your view, if you want to add AJAX validation, just add the following.
<%
Html.EnableClientValidation() ''# This is where all the magic happens. It will build your clientside validation for you out of your MetaData.
Using Html.BeginForm("Edit", "Users")
%>
<!-- all your markup crap -->
<tr>
<td>
<%: Html.LabelFor(Function(model) model.UserName)%></td>
<td>
<%: Html.TextBoxFor(Function(model) model.UserName) %>
<%: Html.ValidationMessage("UserName", "*")%><br />
</td>
</tr>
<!-- somewhere you'll want to add a Validation Summary of all your errors -->
<%= Html.ValidationSummary("Oops!, please correct the errors...") %>
<% End Using%>
<!-- bottom of the page -->
<script src="../../Assets/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Assets/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="../../Assets/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
EDIT:
Here is some info on rendering using Ajax.BeginForm
http://singulartechnologies.com/asp-net-mvc-ajax-beginform-sample-code
http://msdn.microsoft.com/en-us/library/dd381533.aspx
http://weblogs.asp.net/mikebosch/archive/2008/02/15/asp-net-mvc-submitting-ajax-form-with-jquery.aspx
精彩评论