I'm Keyvan Nayyeri, a 25 years old Ph.D. student at
the Computer Science department of
the University of Texas at San Antonio.
I'm also
a Software Architect and Developer and previously held a B.Sc.
degree in Applied Mathematics.
This is my blog where I publish content about various topics specifically Programming Languages and Compilers, Software
Engineering and Programming.
We are at the middle of editorial stage of our book, and I was working on my chapter about AJAX in ASP.NET MVC in the past few days. Ivan had left a valuable comment for me to include a short reference to the JsonResult option to return JSON data to views. I decided to have a short paragraph about the option and leave an exercise for readers to follow up with. Here I also write the whole discussion that may be worth sharing.
In ASP.NET MVC you can write action methods that return a variety of types to be used in your views to obtain data for AJAX interactions. Most common types are string and ActionResult, but there is also an option called JsonResult which returns its values as JSON serialized data. The returned data can be used easily in client-side as appropriate.
Steve Michelotti has a good blog post explaining this topic with an example, and my post may end up with a similar content, but I try to discuss the topic in better details.
Assume that you have a page that contains a button and a list box and you want to add some items to this list box using an AJAX interaction whenever user clicks on the button. Here I implement this scenario and retrieve my data as JSON from my controllers to exhibit the abovementioned topic in action.
First I create a master with the layout of my site and include a reference to jQuery library. Note that I’m going to use jQuery in order to extract data from JSON, but this approach is applicable to anything that can retrieve JSON data; however, jQuery would be the most common one for ASP.NET MVC developers.
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="JsonResultSample.Views.Shared.Site" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>
<%= Html.Encode(ViewData["Title"]) %></title>
<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>
Using JsonResult in ASP.NET MVC AJAX</h1>
</div>
<div id="logindisplay">
</div>
<div id="menucontainer">
<ul id="menu">
<li>
<%= Html.ActionLink("Home", "Index", "Home")%></li>
</ul>
</div>
</div>
<div id="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
<div id="footer">
Keyvan Nayyeri © 2008
</div>
</div>
</div>
</body>
</html>
Now I create a controller especially an action method that returns an instance of JsonResult object.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace JsonResultSample.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Title"] = "Home Page";
ViewData["Message"] = "Filling the List with JSON Data";
return View();
}
public JsonResult GetData()
{
List<ListItem> list = new List<ListItem>() {
new ListItem() { Text = "Keyvan Nayyeri" },
new ListItem() { Text = "Simone Chiaretta" },
new ListItem() { Text = "Scott Guthrie" },
new ListItem() { Text = "Scott Hanselman" },
new ListItem() { Text = "Phil Haack" },
new ListItem() { Text = "Rob Conery" }
};
return this.Json(list);
}
}
}
As you see, I created a list of ListItem objects and then used Json function to serialize my object into JSON format. This method is very powerful and can serialize more complex types as well.
The next and last step is creating a view that renders the appropriate output.
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true"
CodeBehind="Index.aspx.cs" Inherits="JsonResultSample.Views.Home.Index" %>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$.fn.addItems = function(data) {
return this.each(function() {
var list = this;
$.each(data, function(index, itemData) {
var option = new Option(itemData.Text);
list.add(option);
});
});
};
$(function() {
$('#btnClick').click(function() {
$.getJSON("/Home/GetData", null, function(data) {
$("#itemsList").addItems(data);
});
});
});
</script>
<h2>
<%= Html.Encode(ViewData["Message"]) %></h2>
<button id="btnClick" name="btnClick">
Click Me</button>
<br />
<select id="itemsList" name="itemsList" size="6">
</select>
</asp:Content>
Here I have defined the appropriate HTML elements and there is no point to mention about them, but the main code is a jQuery code that retrieves data from my action method and updates the list.
When user clicks on the button, jQuery’s getJSON method extracts data from the action method using its URL, and then passes it to addItems where I add items to the list. Usage of getJSON is the key point here that acts like a bridge between action method and the client. The logic behind addItems is something simple to understand and should be familiar to jQuery developers.
I think that this method is a very handy method and can enhance AJAX interactions in ASP.NET MVC to a great extent.
You can download the source code sample for this post from here.
Using JsonResult in ASP.NET MVC AJAX
Dec 26, 2008 3:11 PM
#
You've been kicked (a good thing) - Trackback from DotNetKicks.com
ASP.NET MVC Archived Buzz, Page 1
Dec 26, 2008 3:41 PM
#
Pingback from ASP.NET MVC Archived Buzz, Page 1
Dew Drop - December 26, 2008 | Alvin Ashcraft's Morning Dew
Dec 26, 2008 6:14 PM
#
Pingback from Dew Drop - December 26, 2008 | Alvin Ashcraft's Morning Dew
Reflective Perspective - Chris Alcock » The Morning Brew #252
Dec 29, 2008 6:34 AM
#
Pingback from Reflective Perspective - Chris Alcock » The Morning Brew #252
Paresh
Feb 12, 2009 1:57 AM
#
Hi,
I am facing one issue while using json in MVC to call
public JsonResult GetData() in ProductController.i changed the script to
$.getJSON("/Product /GetData", null, function(data)
but it is not working.can u pls help me in this ?
efactor
Feb 13, 2009 6:11 AM
#
Not sure where exactly have you put the $.getJSON (.....) call, ideally it should be in Product/Index.aspx in your case.
I tried the above mentioned example as it is and it works 100%. Make necessary adjustment to your code and it should work.
linhtv
Apr 03, 2009 5:09 AM
#
Hi!
I have download a sample of this Ex. But I no run application success, because List<ListItem> is Error. Please help me
Using JsonResult in ASP.NET MVC AJAX : Keyvan Nayyeri
Apr 27, 2009 11:46 AM
#
Thank you for submitting this cool story - Trackback from DotNetShoutout
EricTN
Apr 27, 2009 9:57 PM
#
@linhtv: I had the same build error. You need to add the following using directive to HomeController.cs:
using System.Web.UI.WebControls;
This answer came not from some brilliant analysis on my part, but from ReSharper 4.5 from JetBrains. I double-clicked on the build error and VS put the cursor on the List<ListItem> line, like it no doubt did for you. But because I had ReSharper installed, ReSharper immediately popped a message asking if I wanted to hit Alt-Enter to add the missing using directive. Too helpful! :)
Return JSON objects the right way
Apr 29, 2009 4:12 AM
#
Today I experienced a weird behavior when I was passing JSON string back to a jQuery call using an Ajax
Sam Tyson
May 28, 2009 12:41 PM
#
I had to change one thing to get it to work in FireFox 3:
list.add(option);
changed to:
list.add(option, false);
Pawan
Jun 01, 2009 10:15 AM
#
Thanks for the post. This is something to get/retrieve the data from Controller using JSonResult option. This works FINE..
I was just wondering if anybody knows how to post the data using the same JSon/Akax concept. Posting the Form Data I am talking about!!!
Thanks...
Pawan
Jun 01, 2009 10:22 AM
#
I am adding my comment to previous comment. After submitting this comment, I noticed that this is using some sort of same concept what I am talking about. I am really interested to know this how to post form data using ajax or so without full form submission.
Regards, Pawan
visualseawind
Jun 03, 2009 6:09 AM
#
Following javascript code runs well in IE, but not well in FireFox:
list.add(option)
I used try-catch code to find that 'list' is 'undefined', I've tried 'list.add(option, false)', but got same result.
Why? thanks.
Toan
Jun 17, 2009 3:38 AM
#
Int need include this namespace
using System.Web.UI.WebControls;
:)
Ben
Jun 19, 2009 11:05 PM
#
Couldn't get this to work in Firefox 3.0. Changed...
list.add(option)
.. to ..
list.options.add(option)
.. and it now works in IE and Firefox.
drifter
Dec 08, 2009 11:31 PM
#
thanks a lot.
Amy Grossman
Dec 14, 2009 7:08 AM
#
This post is awesome! I also love your blog quote. :) BTW: Why do the Wrox covers always look like mug shots?.... (It looks like only angry geeks write for them.) Your picture here looks MUCH better. Thanks for the great information!
Amy
Keyvan Nayyeri
Dec 14, 2009 7:55 AM
#
Thanks for your comment.
Wrox has a very restricted guideline for author photos. Besides, I was serving in the armies and couldn't take care of my style those days ;-)
Leave a Comment