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,

 

         public ActionResult CreateUser()
         {
            return View();
         }
         [HttpPost]
         public ActionResult CreateUserPrevious(UserInformation u)
         {
            return View("CreateUserInformation", u);
         }
         [HttpPost]
         public ActionResult CreateUserInformation(UserInformation u)
         {
            if(ModelState.IsValid)
                return View("CreateUserCompanyInformation");
            return View("CreateUserInformation");
         }

         [HttpPost]
         public ActionResult CreateUserCompanyInformation(UserCompanyInformation uc, UserInformation ui)
         {
            if (ModelState.IsValid)
                return Content("Thank you for submitting your information");
            return View("CreateUserCompanyInformation");
         } 

 

          Next create a CreateUser view and add the following lines,

 

         <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<UnobtrusiveValidationWithDynamicContents.Models.UserInformation>" %>

           <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
               CreateUser
           </asp:Content>

           <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
               <div id="dynamicData">
                   <%Html.RenderPartial("CreateUserInformation"); %>
               </div>
           </asp:Content>

 

          Next create a CreateUserInformation partial view and add the following lines,

 

           <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<UnobtrusiveValidationWithDynamicContents.Models.UserInformation>" %>

           <% Html.EnableClientValidation(); %>
           <%using (Html.BeginForm("CreateUserInformation", "Home"))
           { %>
           <table id="table1">
             <tr style="background-color:#E8EEF4;font-weight:bold">
                <td colspan="3" align="center">
                     User Information
                </td>
             </tr>
              <tr>
                <td>
                     First Name
                </td>
                <td>
                     <%=Html.TextBoxFor(a => a.FirstName)%>
                </td>
                <td>
                     <%=Html.ValidationMessageFor(a => a.FirstName)%>
              </td>           
          </tr>
          <tr>
              <td>
                    Last Name
              </td>
              <td>
                    <%=Html.TextBoxFor(a => a.LastName)%>
              </td>
              <td>
                    <%=Html.ValidationMessageFor(a => a.LastName)%>
              </td>           
          </tr>
          <tr>              <td>
                    Email
              </td>
              <td>
                    <%=Html.TextBoxFor(a => a.Email)%>
              </td>
              <td>
                    <%=Html.ValidationMessageFor(a => a.Email)%>
              </td>           
          </tr>
       
          <tr>
              <td colspan="3" align="center">
                    <input type="submit" name="userInformation" value="Next"/>
              </td>
          </tr>
        </table>
    <%} %>
    <script type="text/javascript">
        $("form").submit(function (e) {
            if ($(this).valid()) {
                $.post('<%= Url.Action("CreateUserInformation")%>', $(this).serialize(), function (data) {
                    $("#dynamicData").html(data);
                    $.validator.unobtrusive.parse($("#dynamicData"));
                });
            }
            e.preventDefault();
        });
    </script>

 

          Next create a CreateUserCompanyInformation partial view and add the following lines,

 

     <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<UnobtrusiveValidationWithDynamicContents.Models.UserCompanyInformation>" %>

         <% Html.EnableClientValidation(); %>   
         <%using (Html.BeginForm("CreateUserCompanyInformation", "Home"))
         { %>
           <table id="table1">
             <tr style="background-color:#E8EEF4;font-weight:bold">
                 <td colspan="3" align="center">
                User Company Information
                 </td>
             </tr>
             <tr>
                 <td>
                Company Name
                 </td>
                 <td>
                     <%=Html.TextBoxFor(a => a.CompanyName)%>
                 </td>
                 <td>
                     <%=Html.ValidationMessageFor(a => a.CompanyName)%>
                 </td>           
             </tr>
             <tr>
                 <td>
                Company Address
                 </td>
                 <td>
                     <%=Html.TextBoxFor(a => a.CompanyAddress)%>
                 </td>
                 <td>
                     <%=Html.ValidationMessageFor(a => a.CompanyAddress)%>
                 </td>           
             </tr>
             <tr>
                 <td>
                Designation
                 </td>
                 <td>
                     <%=Html.TextBoxFor(a => a.Designation)%>
                 </td>
                 <td>
                     <%=Html.ValidationMessageFor(a => a.Designation)%>
                 </td>           
             </tr>
       
             <tr>
                 <td colspan="3" align="center">               
                     <input type="button" id="prevButton" value="Previous"/>  
                     <input type="submit" name="userCompanyInformation" value="Next"/>
                     <%=Html.Hidden("FirstName")%>
                     <%=Html.Hidden("LastName")%>
                     <%=Html.Hidden("Email")%>
                 </td>
             </tr>
             </table>
            <%} %>
        <script type="text/javascript">
        $("#prevButton").click(function () {
            $.post('<%= Url.Action("CreateUserPrevious")%>', $($("form")[0]).serialize(), function (data) {
                $("#dynamicData").html(data);
                $.validator.unobtrusive.parse($("#dynamicData"));
            });
        });
        $("form").submit(function (e) {
            if ($(this).valid()) {
                $.post('<%= Url.Action("CreateUserCompanyInformation")%>', $(this).serialize(), function (data) {
                    $("#dynamicData").html(data);
                    $.validator.unobtrusive.parse($("#dynamicData"));
                });
            }
            e.preventDefault();
        });
        </script>

 

          Next create a new class file UserInformation.cs inside Model folder and add the following code,

 

          public class UserInformation
          {
              public int Id { get; set; }

              [Required(ErrorMessage = "First Name is required")]
              [StringLength(10, ErrorMessage = "First Name max length is 10")]
              public string FirstName { get; set; }

              [Required(ErrorMessage = "Last Name is required")]
              [StringLength(10, ErrorMessage = "Last Name max length is 10")]
              public string LastName { get; set; }

              [Required(ErrorMessage = "Email is required")]
              [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email Format is wrong")]
              public string Email { get; set; }
          }

 

          Next create a new class file UserCompanyInformation.cs inside Model folder and add the following code, 

 

          public class UserCompanyInformation
          {
              public int UserId { get; set; }

              [Required(ErrorMessage = "Company Name is required")]
              [StringLength(10, ErrorMessage = "Company Name max length is 10")]
              public string CompanyName { get; set; }

              [Required(ErrorMessage = "CompanyAddress is required")]
              [StringLength(50, ErrorMessage = "Company Address max length is 50")]
              public string CompanyAddress { get; set; }

              [Required(ErrorMessage = "Designation is required")]
              [StringLength(50, ErrorMessage = "Designation max length is 10")]
              public string Designation { get; set; }
          }

 

         Next add the necessary script files in Site.Master,

 

         <script src="<%= Url.Content("~/Scripts/jquery-1.4.4.min.js")%>" type="text/javascript"></script>
         <script src="<%= Url.Content("~/Scripts/jquery.validate.min.js")%>" type="text/javascript"></script>
         <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.


 

3 Comments

Comments have been disabled for this content.