Unobtrusive Client Side Validation with Dynamic Contents in ASP.NET MVC 3
Introduction:
A while ago, I blogged about how to
perform client side validation for dynamic contents in
ASP.NET MVC 2 at
here. Using the approach given in that blog, you can easily
validate your dynamic ajax contents at client side. ASP.NET
MVC 3 also supports unobtrusive client side validation in
addition to ASP.NET MVC 2 client side validation for
backward compatibility. I feel it is worth to rewrite
that blog post for ASP.NET MVC 3 unobtrusive client side
validation. In this article I will show you how to do this.
Description:
I am going to use the same example presented at here. Create a new ASP.NET MVC 3 application. Then just open HomeController.cs and add the following code,
01 |
public
ActionResult CreateUser()
|
02 |
{
|
03 |
return
View();
|
04 |
}
|
05 |
[HttpPost]
|
06 |
public
ActionResult
CreateUserPrevious(UserInformation u)
|
07 |
{
|
08 |
return
View("CreateUserInformation", u);
|
09 |
}
|
10 |
[HttpPost]
|
11 |
public
ActionResult
CreateUserInformation(UserInformation u)
|
12 |
{
|
13 |
if(ModelState.IsValid)
|
14 |
return
View("CreateUserCompanyInformation");
|
15 |
return
View("CreateUserInformation");
|
16 |
}
|
17 |
18 |
[HttpPost]
|
19 |
public
ActionResult
CreateUserCompanyInformation(UserCompanyInformation
uc, UserInformation ui)
|
20 |
{
|
21 |
if
(ModelState.IsValid)
|
22 |
return
Content("Thank you for submitting your
information");
|
23 |
return
View("CreateUserCompanyInformation");
|
24 |
}
|
Next create a CreateUser view and add the following lines,
01 |
<%@ Page Title="" Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<UnobtrusiveValidationWithDynamicContents.Models.UserInformation>" %>
|
02 |
03 |
<asp:Content
ID="Content1"
ContentPlaceHolderID="TitleContent"
runat="server">
|
04 |
CreateUser
|
05 |
</asp:Content>
|
06 |
07 |
<asp:Content
ID="Content2"
ContentPlaceHolderID="MainContent"
runat="server">
|
08 |
<div
id="dynamicData">
|
09 |
<%Html.RenderPartial("CreateUserInformation");
%>
|
10 |
</div>
|
11 |
</asp:Content>
|
Next create a CreateUserInformation partial view and add the following lines,
01 |
<%@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<UnobtrusiveValidationWithDynamicContents.Models.UserInformation>" %>
|
02 |
03 |
<% Html.EnableClientValidation();
%>
|
04 |
<%using
(Html.BeginForm("CreateUserInformation",
"Home"))
|
05 |
{ %>
|
06 |
<table
id="table1">
|
07 |
<tr
style="background-color:#E8EEF4;font-weight:bold">
|
08 |
<td
colspan="3"
align="center">
|
09 |
User Information
|
10 |
</td>
|
11 |
</tr>
|
12 |
<tr>
|
13 |
<td>
|
14 |
First Name
|
15 |
</td>
|
16 |
<td>
|
17 |
<%=Html.TextBoxFor(a =>
a.FirstName)%>
|
18 |
</td>
|
19 |
<td>
|
20 |
<%=Html.ValidationMessageFor(a =>
a.FirstName)%>
|
21 |
</td>
|
22 |
</tr>
|
23 |
<tr>
|
24 |
<td>
|
25 |
Last Name
|
26 |
</td>
|
27 |
<td>
|
28 |
<%=Html.TextBoxFor(a =>
a.LastName)%>
|
29 |
</td>
|
30 |
<td>
|
31 |
<%=Html.ValidationMessageFor(a =>
a.LastName)%>
|
32 |
</td>
|
33 |
</tr>
|
34 |
<tr> <td>
|
35 |
Email
|
36 |
</td>
|
37 |
<td>
|
38 |
<%=Html.TextBoxFor(a =>
a.Email)%>
|
39 |
</td>
|
40 |
<td>
|
41 |
<%=Html.ValidationMessageFor(a =>
a.Email)%>
|
42 |
</td>
|
43 |
</tr>
|
44 |
|
45 |
<tr>
|
46 |
<td
colspan="3"
align="center">
|
47 |
<input
type="submit"
name="userInformation"
value="Next"/>
|
48 |
</td>
|
49 |
</tr>
|
50 |
</table>
|
51 |
<%} %>
|
52 |
<script
type="text/javascript">
|
53 |
$("form").submit(function (e) {
|
54 |
if ($(this).valid()) {
|
55 |
$.post('<%=
Url.Action("CreateUserInformation")%>',
$(this).serialize(), function (data) {
|
56 |
$("#dynamicData").html(data);
|
57 |
$.validator.unobtrusive.parse($("#dynamicData"));
|
58 |
});
|
59 |
}
|
60 |
e.preventDefault();
|
61 |
});
|
62 |
</script>
|
Next create a CreateUserCompanyInformation partial view and add the following lines,
01 |
<%@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<UnobtrusiveValidationWithDynamicContents.Models.UserCompanyInformation>" %>
|
02 |
03 |
<% Html.EnableClientValidation(); %>
|
04 |
<%using
(Html.BeginForm("CreateUserCompanyInformation",
"Home"))
|
05 |
{ %>
|
06 |
<table
id="table1">
|
07 |
<tr
style="background-color:#E8EEF4;font-weight:bold">
|
08 |
<td
colspan="3"
align="center">
|
09 |
User Company Information
|
10 |
</td>
|
11 |
</tr>
|
12 |
<tr>
|
13 |
<td>
|
14 |
Company Name
|
15 |
</td>
|
16 |
<td>
|
17 |
<%=Html.TextBoxFor(a =>
a.CompanyName)%>
|
18 |
</td>
|
19 |
<td>
|
20 |
<%=Html.ValidationMessageFor(a =>
a.CompanyName)%>
|
21 |
</td>
|
22 |
</tr>
|
23 |
<tr>
|
24 |
<td>
|
25 |
Company Address
|
26 |
</td>
|
27 |
<td>
|
28 |
<%=Html.TextBoxFor(a =>
a.CompanyAddress)%>
|
29 |
</td>
|
30 |
<td>
|
31 |
<%=Html.ValidationMessageFor(a =>
a.CompanyAddress)%>
|
32 |
</td>
|
33 |
</tr>
|
34 |
<tr>
|
35 |
<td>
|
36 |
Designation
|
37 |
</td>
|
38 |
<td>
|
39 |
<%=Html.TextBoxFor(a =>
a.Designation)%>
|
40 |
</td>
|
41 |
<td>
|
42 |
<%=Html.ValidationMessageFor(a =>
a.Designation)%>
|
43 |
</td>
|
44 |
</tr>
|
45 |
|
46 |
<tr>
|
47 |
<td
colspan="3"
align="center">
|
48 |
<input
type="button"
id="prevButton"
value="Previous"/>
|
49 |
<input
type="submit"
name="userCompanyInformation"
value="Next"/>
|
50 |
<%=Html.Hidden("FirstName")%>
|
51 |
<%=Html.Hidden("LastName")%>
|
52 |
<%=Html.Hidden("Email")%>
|
53 |
</td>
|
54 |
</tr>
|
55 |
</table>
|
56 |
<%} %>
|
57 |
<script
type="text/javascript">
|
58 |
$("#prevButton").click(function () {
|
59 |
$.post('<%=
Url.Action("CreateUserPrevious")%>',
$($("form")[0]).serialize(), function (data)
{
|
60 |
$("#dynamicData").html(data);
|
61 |
$.validator.unobtrusive.parse($("#dynamicData"));
|
62 |
});
|
63 |
});
|
64 |
$("form").submit(function (e) {
|
65 |
if ($(this).valid()) {
|
66 |
$.post('<%=
Url.Action("CreateUserCompanyInformation")%>',
$(this).serialize(), function (data) {
|
67 |
$("#dynamicData").html(data);
|
68 |
$.validator.unobtrusive.parse($("#dynamicData"));
|
69 |
});
|
70 |
}
|
71 |
e.preventDefault();
|
72 |
});
|
73 |
</script>
|
Next create a new class file UserInformation.cs inside Model folder and add the following code,
01 |
public
class
UserInformation
|
02 |
{
|
03 |
public
int
Id { get; set; }
|
04 |
05 |
[Required(ErrorMessage = "First Name is required")]
|
06 |
[StringLength(10, ErrorMessage = "First Name max length is 10")]
|
07 |
public
string
FirstName { get; set; }
|
08 |
09 |
[Required(ErrorMessage = "Last Name is required")]
|
10 |
[StringLength(10, ErrorMessage = "Last Name max length is 10")]
|
11 |
public
string
LastName { get; set; }
|
12 |
13 |
[Required(ErrorMessage = "Email is required")]
|
14 |
[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email Format is wrong")]
|
15 |
public
string
Email { get; set; }
|
16 |
}
|
Next create a new class file UserCompanyInformation.cs inside Model folder and add the following code,
01 |
public
class
UserCompanyInformation
|
02 |
{
|
03 |
public
int
UserId { get; set; }
|
04 |
05 |
[Required(ErrorMessage = "Company Name is required")]
|
06 |
[StringLength(10, ErrorMessage = "Company Name max length is 10")]
|
07 |
public
string
CompanyName { get; set; }
|
08 |
09 |
[Required(ErrorMessage = "CompanyAddress is required")]
|
10 |
[StringLength(50, ErrorMessage = "Company Address max length is 50")]
|
11 |
public
string
CompanyAddress { get; set; }
|
12 |
13 |
[Required(ErrorMessage = "Designation is required")]
|
14 |
[StringLength(50, ErrorMessage = "Designation max length is 10")]
|
15 |
public
string
Designation { get; set; }
|
16 |
}
|
Next add the necessary script files in Site.Master,
1 |
<script
src="<%= Url.Content("~/Scripts/jquery-1.4.4.min.js")%>"
type="text/javascript"></script>
|
2 |
<script
src="<%= Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
|
3 |
<script
src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%>"
type="text/javascript"></script>
|
Now run this application. You will get the same behavior as described in this article. The key important feature to note here is the $.validator.unobtrusive.parse method, which is used by ASP.NET MVC 3 unobtrusive client side validation to initialize jQuery validation plug-in to start the client side validation process. Another important method to note here is the jQuery.valid method which return true if the form is valid and return false if the form is not valid .
Summary:
There may be several occasions when
you need to load your HTML contents dynamically. These
dynamic HTML contents may also include some input elements
and you need to perform some client side validation for
these input elements before posting thier values to server.
In this article I shows you how you can enable client side
validation for dynamic input elements in ASP.NET MVC 3. I am
also attaching a sample application. Hopefully you will
enjoy this article too.