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