Using MVC Data Annotations for validation with the Infragistics jQuery Editors

Atanas Dyulgerov / Friday, May 04, 2012

One way to enable data validation when using jQuery and MVC is to use data annotations in the data model and then configure the jQuery editors to use them. This article will walk you through this process in the new 2012.1 release.

The first step is to creating the basic ASP.net MVC app with jQuery. Once you create an empty MVC3 project you should add the Infragistics.Web.Mvc.dll assembly to your references. In my case its located in C:\Users\Public\Documents\Infragistics\NetAdvantage 2012.1\jQuery\Samples\MVC\bin\ but it could be somewhere else depending on where you installed the product. Once you add the reference, you should add the css files and the js files that come with the product to your project. I put them in a folder called Infra at the top of the project. The css folder contains the css files hierarchy with styles for all controls and the js folder contains all the required js scripts. We are going to use those folders with the Infragistics loader in a minute when we are creating the View.

Lets create the model. I’m going to name it Person.cs as this article will show how to write a form with validation that creates a user as seen on the screenshot above. It will have three properties: Name, Age and Email.

  1. public class Person
  2. {
  3.     public string Name { get; set; }
  4.     public int Age { get; set; }
  5.     public string Email { get; set; }
  6. }

Once we have the model we can create a controller. Mine will be called PersonController. In there we are going to put two Actions called Create that handle the model in GET and POST modes.

  1. public class PersonController : Controller
  2. {
  3.     public ActionResult Create()
  4.     {
  5.         var person = new Person();
  6.         return View(person);
  7.     }
  8.  
  9.     [HttpPost]
  10.     public ActionResult Create(Person person)
  11.     {
  12.         return View(person);
  13.     }
  14. }

Make sure you add the reference to the namespace in which the model is created.

Once we have the model and the controller we can create a view as well. Lets go ahead and call it Create. The view should be strongly typed, the model class obviously Person. Note: If you don’t see the class Person you just created in the list make sure you build your solution first.

In the view (I assume you use ASPX and no MasterPage) we can start adding the interesting elements. The first one is the inclusion the the Infragistics MVC assembly.

  1. <%@ Import Namespace="Infragistics.Web.Mvc" %>

You can put that right after the Page line.

Then you should add the jQuery scripts. Personally I like using the CDN.

  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  2. <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"
  3.     type="text/javascript"></script>

Note: Make sure you use a current version. If you use an old one some inexplicable exceptions might occur!

Once we are done with that we need to add and initialize the Infragistics loader.

  1. <script type="text/javascript" src="/Infra/js/infragistics.loader.js"></script>
  2. <%= Html.Infragistics()
  3.     .Loader()
  4.     .ScriptPath(Url.Content("~/Infra/js/"))
  5.     .CssPath(Url.Content("~/Infra/CSS/"))
  6.     .Resources("igShared,igValidator")
  7.     .Render()
  8. %>

Like I said in the beginning of the article I put all the scripts and styles from the product in the Infra folder. In your project they could be somewhere else.

The next step is to add the content with the form. here is the code.

  1. <div>
  2.     <% using (Html.BeginForm()) %>
  3.     <% { %>
  4.     <p>
  5.         <%= Html.LabelFor(m => m.Name) %>
  6.         <%= Html.Infragistics()
  7.             .TextEditorFor(m => m.Name)
  8.             .Render() %>
  9.         <%= Html.ValidationMessageFor(m => m.Name) %>
  10.     </p>
  11.     <p>
  12.         <%= Html.LabelFor(m => m.Age) %>
  13.         <%= Html.Infragistics()
  14.             .NumericEditorFor(m => m.Age)
  15.             .Render() %>
  16.         <%= Html.ValidationMessageFor(m => m.Age)%>
  17.     </p>
  18.     <p>
  19.         <%= Html.LabelFor(m => m.Email) %>
  20.         <%= Html.Infragistics()
  21.             .TextEditorFor(m => m.Email)
  22.             .Render() %>
  23.         <%= Html.ValidationMessageFor(m => m.Email)%>
  24.     </p>
  25.     <p>
  26.         <input id="btnSubmit" type="submit" value="Create" />
  27.     </p>
  28.     <% } %>
  29. </div>

The result of this will be a working form that does not have validation.

To add the validation first we need to use the data annotations to describe what the requirements for each property are. Lets go to the Person.cs model file.

Make sure you add the namespace

  1. using System.ComponentModel.DataAnnotations;

Then you can add required fields, string length, regular expression, etc.

  1. public class Person
  2. {
  3.     [Required(ErrorMessage = "Name Required")]
  4.     [StringLength(50, ErrorMessage = "Must be under 50 characters")]
  5.     public string Name { get; set; }
  6.  
  7.     [Required(ErrorMessage = "Age Required")]
  8.     [Range(1, 120, ErrorMessage = "Age must be between 1 and 120")]
  9.     public int Age { get; set; }
  10.  
  11.     [Required(ErrorMessage = "Email Required")]
  12.     [RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$", ErrorMessage = "Not a valid email")]
  13.     public string Email { get; set; }
  14. }

This is just an example. Experiment with those.

This is actually enough to enable the validation.

Now if you want the validation error message to be on the right as on the first screenshot you need to add this line after each editor:

  1. <%= Html.ValidationMessageFor(m => m.Name) %>

And specify which property should the message be displayed for.

You can also provide some styling for the message. The class you need is field-validation-error. You could also style the button to a fancier igButton. Here is the complete code:

  1. <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<DataAnnotationDemo.Models.Person>" %>
  2.  
  3. <%@ Import Namespace="Infragistics.Web.Mvc" %>
  4. <!DOCTYPE html>
  5. <html>
  6. <head runat="server">
  7.     <title>Person</title>
  8.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  9.     <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"
  10.         type="text/javascript"></script>
  11.     <script type="text/javascript" src="/Infra/js/infragistics.loader.js"></script>
  12.     <%= Html.Infragistics()
  13.         .Loader()
  14.         .ScriptPath(Url.Content("~/Infra/js/"))
  15.         .CssPath(Url.Content("~/Infra/CSS/"))
  16.         .Resources("igShared,igValidator")
  17.         .Render()
  18.     %>
  19.     <style type="text/css">
  20.         .field-validation-error
  21.         {
  22.             color: Red;
  23.         }
  24.     </style>    
  25.     <script type="text/javascript">
  26.         $.ig.loader(function () {
  27.             $("#btnSubmit").igButton({ labelText: $("#btnSubmit").val() });
  28.         });
  29.     </script>
  30. </head>
  31. <body>
  32.     <div>
  33.         <% using (Html.BeginForm()) %>
  34.         <% { %>
  35.         <p>
  36.             <%= Html.LabelFor(m => m.Name) %>
  37.             <%= Html.Infragistics()
  38.                 .TextEditorFor(m => m.Name)
  39.                 .Render() %>
  40.             <%= Html.ValidationMessageFor(m => m.Name) %>
  41.         </p>
  42.         <p>
  43.             <%= Html.LabelFor(m => m.Age) %>
  44.             <%= Html.Infragistics()
  45.                 .NumericEditorFor(m => m.Age)
  46.                 .Render() %>
  47.             <%= Html.ValidationMessageFor(m => m.Age)%>
  48.         </p>
  49.         <p>
  50.             <%= Html.LabelFor(m => m.Email) %>
  51.             <%= Html.Infragistics()
  52.                 .TextEditorFor(m => m.Email)
  53.                 .Render() %>
  54.             <%= Html.ValidationMessageFor(m => m.Email)%>
  55.         </p>
  56.         <p>
  57.             <input id="btnSubmit" type="submit" value="Create" />
  58.         </p>
  59.         <% } %>
  60.     </div>
  61. </body>
  62. </html>

I hope this article was useful and interesting to you! Have a great day!