AJAX calls to ASP.NET MVC action methods using jQuery
It is best practice to use jQuery (or similar JavaScript library) for your web development. These libraries provide a powerful JavaScript API that allows you to interact with the DOM. There are many many differences between browsers and even between versions of the same browser. A well designed library, such as jQuery, will take care of these differences for you. You are then allowed to focus on coding your features and not on making sure your code is going to work in IE, Chrome, Safari, and Firefox.
In this post, I will cover how to use jQuery to call the action methods on your ASP.NET MVC controller using AJAX. I will not cover how to use jQuery to select and manipulate DOM elements. The later has been covered quite frequently elsewhere.
Getting Started
Using jQuery with the ASP.NET MVC framework is very easy. Most of you know that jQuery now ships with ASP.NET MVC. To use jQuery you must include the following script tag (usually in your Master Page or the HTML ‘head’ section:
<script src="<%= Url.Content("~/Scripts/jquery-1.3.2.js") %>" type="text/javascript"></script>
This will load the jQuery library from the content folder and make it available on the page.
Call An Action Method That Returns String Content
Imagine you have the following action method on a Test controller:
public string GetDateTimeString() { return DateTime.Now.ToString(); }
Note that the above method returns a string. To call this action method using jQuery, you can use the jQuery ‘get’ function as shown below:
var url = "/Monitor/Test/GetDateTimeString"; $.get(url, null, function(data) { $("#getDateTimeString").html(data); });
The jQuery ‘get’ method is a helper method that generates an AJAX GET request. The first parameter is the URL and the third is the callback function when the response is received. The callback function takes one parameter ‘data’ that holds the string content. The following is a screen shot of the resulting data:
Call An Action Method That Returns A String But Takes Parameters
This is really the same scenario as the previous case, except the action method expects a parameter. To set the action method parameter we will use the second parameter of the jQuery ‘get’ function. Imagine we have this action method on a Test controller:
public string ReverseTheString(string input) { char[] arr = input.ToCharArray(); Array.Reverse(arr); return new string(arr); }
Use the following JavaScript to call this method using AJAX:
var url = "/Monitor/Test/ReverseTheString"; var stringToReverse = "Bob Cravens"; $.get(url, { input: stringToReverse }, function(data) { $("#reverseTheString").html(data); });
Notice that the second parameter to the ‘get’ function now contains a list of key / value pairs. This example supplies one parameter, but can be extended to provide multiple parameters. The result of the above looks like the following:
Call An Action Method That Returns JSON And Takes Parameters
The action methods above returned simple strings. Now imagine you want to dynamically fetch more complex data. This is typically formatted in JSON. For example, imagine we want to fetch contact information from the server. More specifically let’s say you have the following ContactInfo class and GetContactInfo action method:
public class ContactInfo { public string FirstName { get; set; } public string LastName { get; set; } public string State { get; set; } public int Age { get; set; } } public JsonResult GetContactInfo(int personId) { // Use personId to fetch info from repository. // // Fake it here. ContactInfo contactInfo = new ContactInfo { FirstName = "Bob", LastName = "Cravens", State = "Wisconsin", Age = new 43 }; return Json(contactInfo); }
Notice the action method is now returning a ‘JsonResult’. This action method can be called using the following JavaScript:
var url = "/Monitor/Test/GetContactInfo"; var id = 123; $.getJSON(url, { personId: id }, function(data) { $("#name").html(data.FirstName + " " + data.LastName); $("#state").html(data.State); $("#age").html(data.Age); });
Using Firebug we can sniff the response. A screen shot is shown below:
Notice the response data now has JSON format. The following was rendered in this example:
Post Data To An Action Method
Imagine you have a situation where you want to HTTP POST instead of GET data. For example, suppose you have data that you want to submit via AJAX. Assume for instance you have the following action method:
[AcceptVerbs(HttpVerbs.Post)] public string RegisterUser(string firstName, string lastName) { // Use the parameters provided to register a new user. return firstName + " " + lastName + " was successfully registered."; }
This action method has attributes that only accept HTTP POST requests. To call this method using AJAX we can use the jQuery ‘post’ function as follows:
var url = "/Monitor/Test/RegisterUser"; var first = "Bob"; var last = "Cravens"; $.post(url, { firstName: first, lastName: last }, function(data) { $("#registerUser").html(data); });
Notice the ‘post’ function and the ‘get’ function take the same parameters. This is an example of an action method that requires two parameters and returns a string result. This results in the following:
Post Form Data
Let’s say you have the following form for submitting new contact information:
<form id="myForm" action="/Monitor/Test/FormPost" method="post"> <div>First Name: <input name="FirstName" type="text" value="Bob" /></div> <div>Last Name: <input name="LastName" type="text" value="Cravens" /></div> <div>Age: <input name="Age" type="text" value="43" /></div> <input type="submit" value="Save Contact" /> <div id="postResult">?</div> </form>
This from calls the ‘FormPost’ action method on the ‘Test’ controller for the ‘Monitor’ application. The following is the action method called when the form is submitted:
[AcceptVerbs(HttpVerbs.Post)] public string FormPost(ContactInfo contactInfo) { return contactInfo.FirstName + " " + contactInfo.LastName + " (" + contactInfo.Age + ") has been saved."; }
Notice the action method returns a string result. Now assume you want to submit this from using AJAX. This is easily done using the following JavaScript:
var f = $("#myForm"); var url = f.attr("action"); var formData = f.serialize(); $.post(url, formData, function(data) { $("#postResult").html(data); });
This JavaScript shows the power of jQuery. With one ‘serialize’ call all the form’s input data is collected and ready to be sent. We can again sniff the post data using Firebug:
Notice the above action method takes a ‘ContactInfo’ (same as the one introduced earlier) object. No where in this code are we creating this type of object. So who is creating this object? This is the power of the ASP.NET MVC model binder in action. As long as the names (‘FirstName’, ‘LastName’, ‘Age’ in this example) of the input elements match the corresponding property names of the object the model binder will have no problem. The following is a screen shot of the rendered HTML after the form has been submitted:
Load an MVC Partial View
The server is often times the best place to generate your HTML content. Adding dynamically generated content based upon the current application state is often necessary. Suppose you have the following action method on your MVC Test controller:
public ActionResult MyPartialView(string info) { ViewData["info"] = info; return View(); }
This action method is simplistic. It stored some ‘info’ data into the ViewData dictionary and then returns the following partial view.
<span> Your Info: <%= Html.Encode(ViewData["info"]) %> </span>
Again, this is a simple partial view that is dynamically generated to display your input info. This partial view can be loaded into the DOM using the jQuery ‘load’ function as follows:
var url = "/Monitor/Test/MyPartialView"; var info = "This is my information." $("#partialView").load(url, { info: info });
Notice the ‘load’ method is a function attached to every jQuery element that is generated with a selector. The above method replaces the HTML of the element with ID of ‘partialView’ with the dynamically generated HTML from the MVC partial view. Using Firebug to sniff the response shows the following:
Notice the response is HTML. The results look like the following when rendered by the browser.
Summary
Using AJAX to call your ASP.NET MVC controller action methods is very simple using jQuery. The jQuery ‘get’, ‘getJSON’, ‘post’ and ‘load’ functions are easily used to call action methods and handle the returned data.
Action controller input parameters can be sent using JSON key / value notation. The important thing to remember is to match key names to the names of the input parameters. The ASP.NET MVC model binders can even handle matching key names to property names on more complex types.
Returned data types can be simple string, JSON data, or HTML rendered from partial views. This allows the JavaScript callback function to be flexible and designed for the situation. No sense in handling JSON if a simple string will do. If it is a better design to let the server generate the HTML this can be done. Or if you are using JavaScript templating and need JSON data that is also easy.
Over all, using AJAX is easy. Probably the difficult thing is deciding when AJAX is the right tool.
Great post Bob. Not being a full blown JAVA script or jQuery programmer this post helped to re-assure me that syntax errors were not the problem. Information was very succint and to the point – well done. Really helped me alot. Thanks.
That’s the best reference for integrating ASP.NET MVC with jQuery. Really well thought and covering all the different options.
Well done Bob!!
Great Post! As a note for anyone using the MVC 2.0 release. You will need to explicitly allow GET request for JSON.
return Json(object, JsonRequestBehavior.AllowGet);
For some more details check out Craig Stuntz’s blog.
http://blogs.teamb.com/craigstuntz/2009/10/05/38476/
Great article! I echo Simone, the best reference I’ve seen on the working with JQuery, JSON, and ASP.NET MVC.
http://www.livescribe.com/forums/member.php?u=8055&ul21=3 [url=http://www.livescribe.com/forums/member.php?u=8056&ul21=3]cheap tramadol[/url] viagra free viagra [url="http://www.livescribe.com/forums/member.php?u=8054&ul21=3"%5Dfioricet%5B/url%5D [LINK http://www.livescribe.com/forums/member.php?u=8060&ul21=3%5Dcheapest cialis[/LINK] wjya
This is awesome! What a great post of doing it simply. I’m a java developer doing this one off .net project and the concepts are so similar.. your post helped me draw immediate analogies between the two frameworks. great job.. keep it up!
Great, great post. Really helped.
Thanks
Thank you! Really helped!
Excellent. Those examples are so simple. Tutorial writers should learn from the excellence of this post. I am completely new to web development, mvc, and jquery – but now I have total confidence that I can pull off this jquery form stuff. Thank you.
You just saved my sanity with this post (at least for now), thanks for that!
Great work!
Great, very rarely we get to read such article(s), simple yet the explanation is awesome.
Good Stuff Bob…
How about a Post that results in a Redirect?
basically, I would like to post the JSON data to a Controller ActionResult that returns a redirect to another page on a different site…
this does not appear to be supported in a ajax json post to a asp.net mvc controller actionresult…
Suggestions?
What about doing the redirect in the browser? For example, you could POST the JSON data to the Controller. The Controller could return a result that included the URL to redirect to if successful. Then you could set the location via JavaScript.
Thanks Bob . Excellent article .
Hi,
thanks for posting nice article.
but there is a problem with submit button to post form data.
after clicking on submit button page’s original view disappeared and only return output from controller action method is visible on browser .
note form post method only work with input type button.
I think that in my original code, I wrapped the post handler in something like:
$(‘#myForm’).submit(function(evt){
evt.preventDefault();
var f = $(this);
var url = f.attr(“action”);
var formData = f.serialize();
$.post(url, formData, function(data) {
$(“#postResult”).html(data);
});
});
Good one, organized the article up to the point.
Thanks a lot. Very usefull article.
Where to write this JQuery functon?
Inside the Index.cshtml (view) or where?
Really Excellent article .
Thanks Bob .
This is really a nice tutorial, you showed in detail that how to make ajax calls and get maximum benefits from MVC.
Thanks for Sharing
I like here!Because give me more knowlegdge!TKS!
Superb article
Its really helpful
Thanks Bob
Over three years later, and this article is still helpful!! This is one of the best articles I have read in a long time. You really kept it simple while still showing all functionality. Great great great post!!
~Cheers
Really excellent article. Thanks for sharing.
wonderful article.
thank you bob.
Hi,
My dev environment: ASP.NET 4 MVC
If I call from Ajax, a controller method that returns a transformed xml for viewing in MS-Excel; how would I go about displaying that Response in a browser window from the Ajax Success function — data parameter contains the xml?
If I manually save that xml to disk and double-click it, MS-Excel opens and displays the spreadsheet. So I know the xml is valid.
But am uncertain how to get the Ajax Success function to launch a browser window and display either a SaveAs dialog or just open Excel.
thanks
Thanks good tutorial.
I see you share interesting stuff here, you can earn some extra money,
your website has huge potential, for the monetizing method, just
search in google – K2 advices how to monetize a website
Hey! I know this is kind of off topic but I was wondering if you knew where I could
get a captcha plugin for my comment form? I’m using the same blog platform as
yours and I’m having difficulty finding one?
Thanks a lot!
Good day I am so excited I found your webpage, I really found
you by mistake, while I was looking on Yahoo for something
else, Anyways I am here now and would just like to
say many thanks for a marvelous post and a all round interesting blog (I also love the theme/design), I don’t have
time to go through it all at the moment but I have saved
it and also added in your RSS feeds, so when I have time
I will be back to read much more, Please do keep up the excellent job.
Hmm it looks like your site ate my first comment (it was super long) so I
guess I’ll just sum it up what I submitted and say, I’m thoroughly
enjoying your blog. I as well am an aspiring blog blogger but I’m still new
to everything. Do you have any tips for beginner
blog writers? I’d genuinely appreciate it.
I usually do not comment, but after looking at a few
of the remarks here AJAX calls to ASP.NET MVC action methods using jQuery.
I actually do have 2 questions for you if
you do not mind. Could it be only me or does it look as if like a few of these responses
come across like they are coming from brain dead visitors?
😛 And, if you are posting on additional online sites, I would like to follow anything new you have to post.
Would you make a list of the complete urls of your shared pages like your Facebook page, twitter feed,
or linkedin profile?
What’s up everyone, it’s my first go to see at this web site, and piece of writing is really fruitful in support of me,
keep up posting these types of articles.
What’s up, after reading this awesome piece of writing i am also cheerful to share my know-how here with colleagues.
Oh my goodness! Impressive article dude! Thank you so much,
However I am experiencing issues with your RSS. I don’t know the reason why
I can’t join it. Is there anybody else having identical RSS problems?
Anyone who knows the answer will you kindly respond? Thanks!!
That is really interesting, You are a very professional blogger.
I’ve joined your feed and stay up for in search
of extra of your great post. Also, I have shared your website in my social networks
Hey There. I found your weblog the use of msn. That is an extremely smartly written article.
I’ll be sure to bookmark it and come back to read more of your helpful
info. Thank you for the post. I’ll certainly return.
tank youuuuuuuuuuuuu
If some one desires expert view about blogging and site-building afterward i advise him/her
to go to see this website, Keep up the fastidious work.
hi . thanks a lot.
Nice post! Nice post!
Congrats rcravens! This is an excellent article. Thank you very much, from Argentina!
Nice artical!
thanks
thanks alot,very good …