You are on page 1of 7

3/8/2017 AJAX calls to ASP.

NET MVC action methods using jQuery

Home Portfolio About Contact Twitter Facebook Google

RANDOM SPARKS
A DIGITAL PLAYGROUND

HomeWeb AJAX calls to ASP.NET MVC action methods using jQuery

AJAX calls to ASP.NET MVC action methods using jQuery


rcravens Web November 13 2009 46 Comments

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:

1 <script src="<%= Url.Content("~/Scripts/jquery-1.3.2.js") %>"

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:

1 public string GetDateTimeString()


2 {
https://bobcravens.com/2009/11/13/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/ 1/23
3/8/2017 AJAX calls to ASP.NET MVC action methods using jQuery

2 {
3 return DateTime.Now.ToString();
4 }

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:

1 var url = "/Monitor/Test/GetDateTimeString";


2 $.get(url, null, function(data) {
3 $("#getDateTimeString").html(data);
4 });

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:

1 public string ReverseTheString(string input)


2 {
3 char[] arr = input.ToCharArray();
4 Array.Reverse(arr);
5 return new string(arr);
6 }

Use the following JavaScript to call this method using AJAX:

1 var url = "/Monitor/Test/ReverseTheString";


2 var stringToReverse = "Bob Cravens";
3 $.get(url, { input: stringToReverse }, function(data) {
4 $("#reverseTheString").html(data);
5 });

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:

https://bobcravens.com/2009/11/13/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/ 2/23
3/8/2017 AJAX calls to ASP.NET MVC action methods using jQuery

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 lets say you have the following ContactInfo class and
GetContactInfo action method:

1 public class ContactInfo


2 {
3 public string FirstName { get; set; }
4 public string LastName { get; set; }
5 public string State { get; set; }
6 public int Age { get; set; }
7 }
8 public JsonResult GetContactInfo(int personId)
9 {
10 // Use personId to fetch info from repository.
11 //
12 // Fake it here.
13 ContactInfo contactInfo = new ContactInfo
14 {
15 FirstName = "Bob",
16 LastName = "Cravens"
17 State = "Wisconsin"
18 Age = new 43
19 };
20 return Json(contactInfo);
21 }

Notice the action method is now returning a JsonResult. This action method
can be called using the following JavaScript:

1 var url = "/Monitor/Test/GetContactInfo";


2 var id = 123;
3 $.getJSON(url, { personId: id }, function(data) {
4 $("#name").html(data.FirstName + " " + data.LastName);
5 $("#state").html(data.State);
6 $("#age").html(data.Age);
7 });

Using Firebug we can sniff the response. A screen shot is shown below:

https://bobcravens.com/2009/11/13/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/ 3/23
3/8/2017 AJAX calls to ASP.NET MVC action methods using jQuery

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:

1 [AcceptVerbs(HttpVerbs.Post)]
2 public string RegisterUser(string firstName, string lastName)
3 {
4 // Use the parameters provided to register a new user.
5 return firstName + " " + lastName + " was successfully registered."
6 }

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:

1 var url = "/Monitor/Test/RegisterUser";


2 var first = "Bob";
3 var last = "Cravens";
4 $.post(url, { firstName: first, lastName: last }, function
5 $("#registerUser").html(data);
6 });

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

Lets say you have the following form for submitting new contact
information:

1 <form id="myForm" action="/Monitor/Test/FormPost" method="post"


2 <div>First Name: <input name="FirstName" type="text" value
3 <div>Last Name: <input name="LastName" type="text" value
4 <div>Age: <input name="Age" type="text" value="43" /></

5 <input type="submit" value="Save Contact" />


https://bobcravens.com/2009/11/13/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/ 4/23
3/8/2017 AJAX calls to ASP.NET MVC action methods using jQuery

5 <input type="submit" value="Save Contact" />


6 <div id="postResult">?</div>
7 </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:

1 [AcceptVerbs(HttpVerbs.Post)]
2 public string FormPost(ContactInfo contactInfo)
3 {
4 return contactInfo.FirstName + " " + contactInfo.LastName +
5 }

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:

1 var f = $("#myForm");
2 var url = f.attr("action");
3 var formData = f.serialize();
4 $.post(url, formData, function(data) {
5 $("#postResult").html(data);
6 });

This JavaScript shows the power of jQuery. With one serialize call all the
forms 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:

https://bobcravens.com/2009/11/13/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/ 5/23
3/8/2017 AJAX calls to ASP.NET MVC action methods using jQuery

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:

1 public ActionResult MyPartialView(string info)


2 {
3 ViewData["info"] = info;
4 return View();
5 }

This action method is simplistic. It stored some info data into the ViewData
dictionary and then returns the following partial view.

1 <span>
2 Your Info: <%= Html.Encode(ViewData["info"]) %>
3 </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:

1 var url = "/Monitor/Test/MyPartialView";


2 var info = "This is my information."
3 $("#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:

https://bobcravens.com/2009/11/13/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/ 6/23
3/8/2017 AJAX calls to ASP.NET MVC action methods using jQuery

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.

Tags: ajax, asp.net, jquery, mvc

About Author

rcravens
https://bobcravens.com/2009/11/13/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/ 7/23

You might also like