ASP.NET MVC Tip: Ajax and Validations using jQuery

jQuery is now part of the ASP.net development platform and it is going to ship with Visual Studio in the future and will also be the part of ASP.NET MVC installation. ASP.NET MVC will be the first product to include jQuery. Guru Gu’s blog entry has the full details regarding this. This is a great decision from Microsoft and I hope that the community would be happy about the great decision taken by Microsoft. And this is another good step for web development after the ASP.NET MVC technology. jQuery is an excellent java script library and very popular among the web developers regardless of technology. In this post, I demonstrate how to integrate jQuery with ASP.NET MVC and will be explain how to send Ajax requests and also show client side validation using jQuery. I am using a blog application for this demo and it will show how to post a comment of a blog entry using Ajax request and will also show partial rendering with the help of a user control.

The below is the class diagram of the example I have used for this demo.  

 

Controller

The below is the code of BlogController. It has two action methods and first one is for getting the single blog post including all comments and another action is for post a comment for the particular blog post. I am going to call the AddComment method ( ActionName Post) using Ajax request using jQuery.

public class BlogController : Controller{

private readonly ICommentRepository comments =new CommentRepository();

private readonly IPostRepository posts = new PostRepository();


[AcceptVerbs( "GET" )] 

public ActionResult Post( int id )

{

 return View( posts.Retrieve().Where( p => p.ID == id ).Single() );

 }


[AcceptVerbs( "POST" )]

[ActionName( "Post" )] 

public ActionResult AddComment( int postId, string commentAuthor, string commentText )  {  

var comment = new Comment{

PostID = postId

Author = commentAuthor

Text = commentText,    

DatePosted = DateTime.Now

};

try {  

      comments.Create( comment );

      return View("PostComment", comment);   

    } 

catch( Exception  ex

  {  

    throw ex;   

  }  

}


View

<asp:Content ID="content" ContentPlaceHolderID="MainContent" runat="server">

<h2>

<% =Html.ActionLink( ViewData.Model.Title,"Post",

new { id = ViewData.Model.ID } )%>

</h2>

<div>Posted by <strong><% =ViewData.Model.Author%>

</strong> on <strong><% =ViewData.Model.DatePosted%></strong>

</div>

<p>

<% =ViewData.Model.Text.Replace( "\n", "<br />" )%>

</p>

<h3>Comments</h3>

<div id="post_comment">

<% if( ViewData.Model.Comments.Count > 0 )

{ %>

<%foreach( var comment in ViewData.Model.Comments )

{ %>  

 <% Html.RenderPartial("PostComment", comment); %>

 <% } %> 

<% } %>

</div><form id="new_comment" action="/Blog/Post" method="post">

<input type="hidden" name="postId" id="postId" value="<% =ViewData.Model.ID%>" />

<img id="ajaxLoader" src="../../Content/ajax-loader.gif"/>

<fieldset> 

 <legend>Add Comment</legend>

  <ul><li>  

    <label for="author"><span class="required">Name: </span></label>

    <input id="commentAuthor" class="text required" name="commentAuthor" type="text" value="" />   

  </li> <li>

<label for="text"><span class="required">Comment: </span></label> 

<textarea cols="20" id="commentText" class="text required" name="commentText" rows="2"></textarea>

 </li> </ul></fieldset>

  <input type="submit" value="Add" />

  </form> </asp:Content>

Displaying the comments

<% if( ViewData.Model.Comments.Count > 0 )

{ %>

<%foreach( var comment in ViewData.Model.Comments )

{ %>  

 <% Html.RenderPartial("PostComment", comment); %>

 <% } %> 

<% } %>

 

The above code iterating through Comments collection of our ViewData and also calling the PostComment user control with comment object as ViewData for displaying a single comment.  This user control is also using for partial rendering when we send Ajax request.

 PostComment.ascx

<u><% =ViewData.Model.Author%> commented on

<% =ViewData.Model.DatePosted%>:</u><p>

<% =ViewData.Model.Text%></p

 

Client Side Validation

 For client side validation, I am using jQuery Validation plugin. For more details about the jQuery plugin, visit http://bassistance.de/jquery-plugins/jquery-plugin-validation/ . This validation framework is very easy to use. You just put class="text required" for a required field validator. For an email validation, you need to put class="text email".  

<input id="commentAuthor" class="text required" name="commentAuthor" type="text" value="" />

<textarea cols="20" id="commentText" class="text required" name="commentText" rows="2"></textarea> 

The validation process will be working with the jQuery method validate of form object.

$(function() {

// for highlight

var elements = $("input[type!='submit'], textarea, select");

elements.focus(function(){

$(this).parents('li').addClass('highlight');

});

elements.blur(function()

{

$(this).parents('li').removeClass('highlight');

});  

$("#new_comment").validate() // for validation

});

You can optionally add validation rules along with validate method. The below code added validation rules included with validate method of form object.

$("#new_comment").validate({

              rules: {

                    

                     commentText: "required",

                     commentAuthor: {

                           required: true,

                           minlength: 2

                     },                  

                     email: {

                           required: true,

                           email: true

                     }

              },

              messages: {

                commentText: "Please enter Comment"                 

                commentAuthor: {

                     required: "Please enter your Name"

                     minlength: "Your Name must consist of at least 2 characters"                                },                  

                     email: " Please enter a valid email address”

              }

       });

jQuery includes

<script type="text/javascript" src="../../Content/jquery-1.2.5.min.js"></script>

<script src="../../Content/jquery.validate.js" type="text/javascript"></script>

 Ajxa using jQuery 

$(document).ready(function() { 

$("#ajaxLoader").hide();

$("#new_comment").submit(function()

  addComment(this);

   return false;  

});

});

jQuery method $(document).ready() will executes when the DOM has been loaded and in this function we handles the onsubmit event of the form. In the onsubmit event, we calling the addComment function and then the return false statement prevent the form submit and we submit the form post using Ajax.

addComment function

function addComment(form)

{

$("#ajaxLoader").show(); 

$.ajax(

{type: form.method,

url: form.action,

data: $(form).serialize(),// Form data

dataType: "html",

completed: $("#ajaxLoader").hide(),

success: function(result)  

var domObj = $(result); // create element from result html                 $("#post_comment").append(domObj); // append to end of comment list 

}, 

error: function(error

  alert(error);  

});    

The above code sends the form data to the controller action Post using Ajax . The dataType: "html" represent that we want partial HTML result for our Ajax request.  In the success function of our Ajax request, we append the result HTML to the <div> element named post_comment. This will dynamically add the new comment to the end of the comment list. 

success: function(result)

{  

 var domObj = $(result);// create element from result html                 $("#post_comment").append(domObj); // append to end of comment list 

}

Controller Action

[AcceptVerbs( "POST" )]

[ActionName( "Post" )] 

public ActionResult AddComment( int postId, string commentAuthor, string commentText )  {  

var comment = new Comment{

PostID = postId

Author = commentAuthor

Text = commentText,    

DatePosted = DateTime.Now

};

try {  

      comments.Create( comment );

      return View("PostComment", comment);   

    } 

catch( Exception  ex

  {  

    throw ex;   

  }  

}

 }

Our Ajax request will call the AddComment method and this will create a new comment for the given Post. After the data persist, we calling the  return View("PostComment", comment). PostComment is our user control with new added comment object as the model of our View. So that the user control will generates markup for the new comment and our Ajax request will get the output as the HTML that rendered by the user control. So we can dynamically add the new markup to the HTML element of our post comment list. User control is very powerful technique for partial rendering. You can download the jQuery from http://docs.jquery.com/Downloading_jQuery and jQuery validation pugin from http://bassistance.de/jquery-plugins/jquery-plugin-validation. You can read Rick Strahl’s excellent article about jQuery from here.

 

Update : You can download the source code from MVCjQuery.zip

Attachment: MVCjQuery.zip
Published Wednesday, October 1, 2008 2:03 AM by shiju
Filed under: , ,

Comments

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Friday, October 3, 2008 1:42 AM by Mike

Excellent article. User control is really a powerful thing.

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Wednesday, November 12, 2008 7:28 AM by bipin

Excellent article.

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Sunday, November 16, 2008 8:29 PM by jenyyoung

Good article.

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Sunday, January 18, 2009 3:16 PM by ash143gupta

This is a very nice article and you have covered most of the points required to kickstart the development with Jquery and MVC

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Thursday, February 19, 2009 7:05 AM by naveedkamboh

Thanks,  I am going to start work with MVC and this is good example.  

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Tuesday, March 3, 2009 9:29 PM by Jim Speaker

Thanks, you just tied together the last little tidbit for me as I prepare to port my .NET 2.0 AJAX app to MVC 3.5 AJAX with jQuery.  'preciate the fine article.  Cheers.

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Saturday, March 14, 2009 11:05 AM by ...

Sehr wertvolle Informationen! Empfehlen!

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Saturday, March 14, 2009 11:06 AM by ...

Sehr wertvolle Informationen! Empfehlen!

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Saturday, April 25, 2009 3:22 PM by marquinhocb

A better approach to doing client-side validation (more automated and uses the same validation for client-side and server-side):

http://xval.codeplex.com

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Friday, July 2, 2010 3:00 AM by Ann

Thanks for information!

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Wednesday, September 1, 2010 10:07 AM by Simonas

And why someone would think this is better then web forms, I can do the same thing as here much faster..

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Thursday, October 7, 2010 2:19 AM by link building service

tis is really a great info..thanks lol!!i would definitely pass on this blog to my frnds..

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Wednesday, May 18, 2011 1:22 AM by philippines seo

Thank you for the scripts on Unique ID Tags in ASP.net, they are helpful as I will be working with them on my thesis.

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Tuesday, June 14, 2011 10:11 PM by Houston Alarm Companies

You have done a marvelous job by exploring this subject with such an honesty and depth. Thanks for sharing it with us!

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Thursday, June 23, 2011 4:15 AM by web design australia

Though Ajax has automatic validations on itself, it does not extend with JQuery, which is why we use libraries and extensions for JQuery in achieving automatic extensions.

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Friday, June 24, 2011 3:44 AM by calgary web design company

Great information. But where can I find the neat DateTimePicker control combo?

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Wednesday, February 8, 2012 8:52 AM by Webdesigner

As a user of jQuery I amazed to read that excellent content. I think this tutorial really optimistic though kinda educative and so far for me. Thanks!

# re: ASP.NET MVC Tip: Ajax and Validations using jQuery

Friday, July 27, 2012 11:52 PM by Whitelabel SEO Service Philippines

This is exactly what I needed for my writeup on jQuery. I think this is excellent content! Thanks!

Leave a Comment

(required) 
(required) 
(optional)
(required)