Posts
202
Comments
1112
Trackbacks
51
MVC JSON - JsonResult and jQuery

The latest release of the MVC framework provides the JsonResult for Controller actions.  I was surprised that I did not find a weatlh of examples for usage so I figured it shouldn't be too hard to get a decent example going.  It turns out, it was even easier than I anticipated.  I wanted to create an example where I would invoke an AJAX call to dynamically populate a dropdown list. 

jQuery has recently received a huge surge of interest of the ASP.NET MVC community so I've been getting up to speed on it myself.  I am quickly turning into a true believer and I've been impressed not only with how few lines of javascript it takes me to get things done but also how (relatively) easy it was to learn.  In addition to numerous examples on the jQuery web site I also recommend jQuery In Action.

Getting an AJAX request with jQuery and JSON in MVC is actually pretty simple.  The first step is to have a Controller action that returns a JsonResult:

   1:  public JsonResult GetStateList()
   2:  {
   3:      List<ListItem> list = new List<ListItem>() {
   4:          new ListItem() { Value = "1", Text = "VA" },
   5:          new ListItem() { Value = "2", Text = "MD" },
   6:          new ListItem() { Value = "3", Text = "DC" }
   7:      };
   8:      return this.Json(list);
   9:  }

Here I'm using the System.Web.Mvc.ListItem class (which is used as items in the SelectList) to simply return a contrived list of US states to populate a dropdown list.  All I have to do is call the Json() method passing in my object and it will automatically be serialized to JSON.  When the request is made the AJAX call can be seen in the Web Development Helper which is an invaluable tool to any AJAX development:

Notice the "application/json" in the request header and the textual representation of the JSON that is being returned from my JSON controller action.

The jQuery to make this happen is quite succinct:

   1:  <script type="text/javascript">
   2:  $(function() {
   3:      $('#btnFillList').click(function() {
   4:          $.getJSON("/Home/GetStateList", null, function(data) {
   5:              $("#stateList").fillSelect(data);
   6:          });
   7:       });
   8:       
   9:       $('#btnClearList').click(function() {
  10:          $("#stateList").clearSelect();
  11:       });
  12:  });
  13:  </script>

Notice on line #4 the use of the $.getJSON() jQuery method.  Then I've simply written a re-usable jQuery method called fillSelect() which will work on the JSON format returned by the ListItem class returned by my controller action:

   1:  $.fn.clearSelect = function() {
   2:      return this.each(function() {
   3:          if (this.tagName == 'SELECT')
   4:              this.options.length = 0;
   5:      });
   6:   } 
   7:   
   8:  $.fn.fillSelect = function(data) {
   9:      return this.clearSelect().each(function() {
  10:          if (this.tagName == 'SELECT') {
  11:              var dropdownList = this;
  12:              $.each(data, function(index, optionData) {
  13:                  var option = new Option(optionData.Text, optionData.Value);
  14:                  
  15:                  if ($.browser.msie) {
  16:                      dropdownList.add(option);
  17:                  }
  18:                  else {
  19:                      dropdownList.add(option, null);
  20:                  }
  21:              });
  22:          }
  23:      });
  24:   }

On line #13 above you'll see the strongly-typed "Text" and "Value" properties that I have the luxury of using because of the native JSON serialization into objects.

The complete code sample can be downloaded here.  It's barely 50 lines of code in all.

posted on Saturday, June 28, 2008 7:35 AM Print
Comments
Gravatar
# re: MVC JSON - JsonResult and jQuery
Rony Braga
7/31/2008 3:41 PM
Great example!

The code would be more clear if you had used Dictionary<> instead of listItem.

In addicition you could create a helper method to return HTML code to render the control.
Gravatar
# re: MVC JSON - JsonResult and jQuery
Steve
7/31/2008 4:34 PM
Rony - Thanks for the response. You can't use a Dictionary because internally the Dictionary keeps it's own order based on the hashing algorithm. The ListItem keeps the correct order.

For the helper method, the "fillSelect()" is the helper method. Unless you were talking about a server side method that renders the client side jQuery code. If so, that's an interesting idea. I guess this would have to take several parameters though: a control which initiates the ajax request, the controller, the action, and the target dropdown control to fill.
Gravatar
# re: MVC JSON - JsonResult and jQuery
pete
9/23/2008 10:55 AM
Great example. It really shows off what can be done with Jquery, MVC and Json.

In real life I believe that the Ajax and Json is not going to be used for inital load of the page. I think an ordinary View would be less code. Once the page is loaded if you have dynamic parts of your page then the Jquery-Ajax and Json are going to come into play. A search page where the critera was at the top and the resluts at the bottom would be a good case for Jquery-Ajax Jason. A photo gallery with star rating for each picture. As user press star JQuery-Ajax updates db via json. A shoping cart would be another canidate for JQuery-Ajax.
Gravatar
# re: MVC JSON - JsonResult and jQuery
Steve
9/24/2008 1:26 PM
Pete - thanks for the comment and those are all good examples. However, I think we're going to see more and more uses for AJAX even on the initial page load. It's often said that a singe-page web app is the "holy grail" for a pure ajax developer. If you look at sites like PageFlakes (http://www.pageflakes.com/) you'll see that *everything* is AJAX including the initial load.
Gravatar
# re: MVC JSON - JsonResult and jQuery
Steve
9/24/2008 10:07 PM
Tom - You can get JSON with the MicrosoftAjax.js by using the Sys.Net.WebRequest invoke Method - the documentation can be found here: http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys.Net/WebRequestClass/WebRequestInvokeMethod.aspx.

Additionally, this post shows an example for doing this: http://weblogs.asp.net/stephenwalther/archive/2008/09/06/asp-net-mvc-tip-41-creating-cascading-dropdown-lists-with-ajax.aspx
Gravatar
# re: MVC JSON - JsonResult and jQuery
Justin
11/14/2008 8:46 PM
Sweet stuff. Really liking the combination of jQuery, JSON, and MVC. I still can't believe it's coming from Microsoft because it's... timely and trendy.

Thanks for the example - I didn't know about ListItem and was previously passing generic lists.
Gravatar
# re: MVC JSON - JsonResult and jQuery
Doug Wilson
12/2/2008 5:39 PM
Great post! I found this immensely useful.

You can also do this:

public JsonResult GetCityList()
{
var list = from city in repository.Cities.GetAll()
select new { Text = city.Name, Value = city.ID };
return Json(list.ToList());
}

This works really well in the Action, particularly when your type is more complex than what is required to populate a drop down list.
Gravatar
# re: MVC JSON - JsonResult and jQuery
Tsinghua
2/15/2009 7:57 PM
I find the answer I want. Thx.
Gravatar
# re: MVC JSON - JsonResult and jQuery
Laurentiu Macovei
3/4/2009 5:12 PM
What about if we need to return a cross-domain JsonP?
Gravatar
# re: MVC JSON - JsonResult and jQuery
AndrewO
3/9/2009 10:25 AM
Great Post. Imagine how responsive an application can be if it is pure AJAX with JQuery calls.
AO
Gravatar
# re: MVC JSON - JsonResult and jQuery
Steve
3/9/2009 10:30 AM
@Laurentiu Macovei:

I've never attempted to use JsonP in the context of MVC returning JSON. In general, I would look at this as a solution for a single domain. If you're wanting to build a web service that is truly a stand-alone web service that could be consumed by other domains, then I'd probably go with WCF rather than MVC. Here is an example: http://msdn.microsoft.com/en-us/library/cc716898.aspx
Gravatar
# re: MVC JSON - JsonResult and jQuery
Binal Shah
4/15/2009 6:01 AM
hi,
MVC application + homecontroler.cs + create.aspx + in asp.net page, i m using some html and asp.net controls (button,gridview).Now i want visibilty of gridview control is visible false and when i m click of button the visibilty of gridview must be true.what code i have to use for this with java script.
please help me out.........................
Gravatar
# re: MVC JSON - JsonResult and jQuery
Binal Shah
4/15/2009 6:02 AM
hi,
MVC application + in asp.net page, i m using some html and asp.net controls (button,gridview).Now i want visibilty of gridview control is visible false and when i m click of button the visibilty of gridview must be true.what code i have to use for this with java script.
please help me out.........................
Gravatar
# re: MVC JSON - JsonResult and jQuery
Steve
4/15/2009 8:54 AM
@Binal - You are not meant to use ASP.NET server controls (like the grid view) in an MVC application. You should ensure that your <form> tag does *not* have a runat="server" attribute in it.

To accomplish what you're seeking in MVC, you can essentially just follow the example above. When you click the button, you make an AJAX call which gets HTML from a controller action (this HTML being your grid) and then populates a <div> tag. This is a different approach than simply hiding/showing a control. Here is another example (though it was based on an old version of MVC): http://geekswithblogs.net/michelotti/archive/2008/07/06/mvc-componentcontroller-vs.-viewusercontrol.aspx
Gravatar
# re: MVC JSON - JsonResult and jQuery
N
5/8/2009 4:09 PM
My Comment
Gravatar
# re: MVC JSON - JsonResult and jQuery
steve
6/5/2009 11:05 AM
Seems like the basic idea being explored here could be librarized along side the other HTML input controls and we could have a self-generating, self-documenting CRUD to serve as front end to the db.
Gravatar
# re: MVC JSON - JsonResult and jQuery
Chris
6/22/2009 11:07 AM
Nice. Never thought it would be quite that easy!
Gravatar
# re: MVC JSON - JsonResult and jQuery
Anonymous
6/28/2009 5:49 PM
dude, stop saying everything is "easy". I'm sure it took you some time to figure this all out. I hate posters who say it's all easy when it's not. Even if jQuery makes it "eaiser" you sill have to understand the ins and outs of jQuery and learn how to parse through, etc.
Gravatar
# re: MVC JSON - JsonResult and jQuery
Tech Freaks
7/12/2009 10:14 PM
Nice article.

You can check a similar simple example for using Jquery/JSON for autopopulate select at http://www.tech-freaks.in/Java-Programming/Javascripts/jquery-json.html
Gravatar
# re: MVC JSON - JsonResult and jQuery
consacepo
8/23/2009 6:59 AM
I've never attempted to use JsonP in the context of MVC returning JSON. In general, I would look at this as a solution for a single domain. If you're wanting to build a web service that is truly a stand-alone web service that could be consumed by other domains, then I'd probably go with WCF rather than MVC. Here is an example: http://msdn.microsoft.com/en-us/library/cc716898.aspx

consacepo
Gravatar
# re: MVC JSON - JsonResult and jQuery
congcong
11/12/2009 12:45 AM
Great example!

I want to ask a question ,how can do if the DataSet instead of List<ListItem>
Gravatar
# re: MVC JSON - JsonResult and jQuery
Steve
11/13/2009 10:44 AM
@congcong - a DataSet is not a good candidate for a structure to be serialized to Json. I would put the contents of the DataSet into a SelectList before sending across the wire.
Gravatar
# re: MVC JSON - JsonResult and jQuery
congcong
11/30/2009 3:28 AM
thankyou for your suggestion
Gravatar
# re: MVC JSON - JsonResult and jQuery
jvm
12/17/2009 2:52 PM
I have controller method
test(string id, string temp, string day)
{
}
my temp value can be microsoft and google and ipod, how should i call using getJSON
I am using
$getJSON (url, function(json){});
where url = ['./controller/methodname'].join('')
but it gives error. If i set temp = "microsft" only, it works. So long string it is breaking. what can be issue?
ANy help?
Gravatar
# re: MVC JSON - JsonResult and jQuery
Serjik
7/13/2010 5:50 AM
It was great, tnx
Gravatar
# re: MVC JSON - JsonResult and jQuery
Paresh Rathod
8/6/2010 1:15 AM
Great Post.

But I am facing a problem.

When I click on, submit button, controller's method is called and return json result.

But my callback functions are not fired or called.

So I m unable to fill my dropdown list.

View file code is as follows:

<script language="javascript" type="text/javascript">
$(document).ready(function() {

$("#btnFillDDL").click(function() {

$.getJSON("Home/GetStateList", null, function(data) {
$("#stateList").fillSelect(data);
});
});


$.fn.clearSelect = function() {
alert('Hi');
return this.each(function() {
if (this.tagName == 'SELECT')
this.option.length = 0;
});
}

$.fn.fillSelect = function(data) {
alert(this.tagName);
return this.clearSelect().each(function() {

if (this.tagName == "SELECT") {
var dropdownList = this;

$.each(data, function(index, optionData) {
var option = new Option(optionData.Text, optionData.Value);
alert(index);
if ($.browser.msie) {
dropdownList.add(option);
}
else {
dropdownList.add(null);
}

});
}
});
}
})
</script>

<% using (Html.BeginForm())
{ %>
<h2>
<%= Html.Encode(ViewData["Message"]) %></h2>
<p>
To learn more about ASP.NET MVC visit
http://asp.net/mvc
.
</p>
<p>
<select id="stateList">
</select>
</p>
<p>
<input type="submit" id="btnFillDDL" value="Fill State" />
</p>
<% } %>

Please help me.

Thanks in advance
Gravatar
# re: MVC JSON - JsonResult and jQuery
Steve Michelotti
8/6/2010 7:28 AM
@Paresh - Did you put the functions fillSelect() and clearSelect() in a separate *.js file? You should do that given these would be re-usable functions that you'd use in multiple areas of your application. Then make sure that you've included that javascript file *before* your code:

<script type="text/javascript" src="/scripts/jquery.fillSelect.js"></script>

<script language="javascript" type="text/javascript">
$(document).ready(function() {

$("#btnFillDDL").click(function() {

$.getJSON("Home/GetStateList", null, function(data) {
$("#stateList").fillSelect(data);
});
});
</script>

Those functions have to be defined *first* before they are called. My guess is that might be what you're running into. Also, you can download the sample code from the link in the post above and ensure that is running successfully for you.
Gravatar
# re: MVC JSON - JsonResult and jQuery
Tenh
9/25/2010 4:29 AM
Dear all,

I do all the step that you mentioned in above but it's not work and i also download your soft codes too for testing but it's still not work, how can i do? can u tell me because i need to know it's very much.
Gravatar
# re: MVC JSON - JsonResult and jQuery
J K
11/30/2010 11:28 AM
I found that ListItem does not exist anymore in the mvc namespace, but this post was helpful: http://stackoverflow.com/questions/494156/does-system-web-mvc-listitem-no-longer-exist-in-asp-net-mvc-rc
Gravatar
# re: MVC JSON - JsonResult and jQuery
Biruk
2/19/2011 4:02 PM
Great post. Worked like charm!
Gravatar
# re: MVC JSON - JsonResult and jQuery
PKS
2/26/2011 5:15 PM
I am bit confuse. Is this a AJAX call? Because for AJAX call in jquery we should use $.ajax is it?
Gravatar
# re: MVC JSON - JsonResult and jQuery
Derek Morrison
4/6/2011 9:13 AM
I noticed the Selected field in the JSON data. Did you omit this in the other code?
Gravatar
# re: MVC JSON - JsonResult and jQuery
Steve
4/7/2011 6:27 AM
@Derek - That post is very old and was using a beta release of MVC back in summery 2008. Use SelectListItem instead of ListItem.
Gravatar
# re: MVC JSON - JsonResult and jQuery
sarsnake
11/9/2011 4:36 PM
Your example, while nicely laid out, doesn't work for me. I replaced the ListItem with SelectedListItem, Json is still not valild and getJSON doesn't fire....please update this tutorial to avoid confusing people. thanks!
Gravatar
# re: MVC JSON - JsonResult and jQuery
andree
1/7/2012 1:40 AM
Thanks for the code. That's really useful for a project I'm working on with this muay thai website.
Gravatar
# re: MVC JSON - JsonResult and jQuery
Salman ansari
6/8/2012 6:48 AM
nice tutorial..specially to beginner like me
ThankYou So much
Gravatar
# re: MVC JSON - JsonResult and jQuery
gaurav
4/17/2013 12:36 AM
great post: really works for me.
Gravatar
# re: MVC JSON - JsonResult and jQuery
Cristian Umaña
6/21/2013 1:25 AM
Great post.
By the way, this code works superb with "chosen" jquery plugin. http://harvesthq.github.io/chosen/
Thanks.

Using your states json example:
options = [{"selected":false,"text":"VA","value":"1"},{"selected":true,"text":"MD","value":"2"},{"selected":false,"text":"DC","value":"3"}];

I just added one more line to "$.fn.fillSelect" to set MD state as default option.

//file fillSelect.js
(function($) {
$.fn.clearSelect = function() {
return this.each(function() {
if (this.tagName == 'SELECT')
this.options.length = 0;
});
};

$.fn.fillSelect = function(data) {
return this.clearSelect().each(function() {
if (this.tagName == 'SELECT') {
var dropdownList = this;
$.each(data, function(index, optionData) {
var option = new Option(optionData.text, optionData.value);
option.selected = optionData.selected; //This line set an option as selected
if ($.browser.msie) {
dropdownList.add(option);
}
else {
dropdownList.add(option, null);
}
});
}
});
};
})(jQuery);

//Using it on another file
options = [{"selected":false,"text":"VA","value":"1"},{"selected":true,"text":"MD","value":"2"},{"selected":false,"text":"DC","value":"3"}];
$('stateList').fillSelect(options);
$('stateList').chosen();
$('stateList').trigger("liszt:updated");

¡Pura Vida!
Gravatar
# re: MVC JSON - JsonResult and jQuery
jayant
7/30/2013 3:16 PM
good work
Keep it up
Gravatar
# re: MVC JSON - JsonResult and jQuery
Bhavik
9/4/2014 12:40 AM
Great example...

Post Comment

Title *
Name *
Email
Comment *  
 

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud