After Thought

Using JsonResult with jquery in ASP.net MVC

with 17 comments

Action methods on controllers return JsonResult (Java Script Object Notation result) that can be used in AJAX application. With the growing popularity of jquery,  jquery is becoming the number 1 choice for AJAX. With this in mind, let us build a simple ASP.net MVC application that returns a JsonResult and we will use jquery to parse the Json and display it accordingly on the web page. Let’s say, we have a page that has 3 fields UserId, LastName and FirstName and we want to populate LastName and FirstName based on the UserId entered.

user_screen

If we type in a UserId and then press Populate User Details, we should see the LastName and FirstName textboxes filled in with the appropriate information if the UserId is found in the repository.

user_screen

If the UserId is not found in the repository, we should get an error message “No UserId found for TestUser”.

user_screen

First let us look at the javascript function that would call the controller action to get the user details. Make sure you have included the latest jquery library in your application. Add the below script to your page.


	function populateUserDetails() {
		var user = {};
		user.UserId = $("#UserId").val();
		$.getJSON("PopulateDetails", user, updateFields);
	};

	updateFields = function(data) {
		$("#LastName").val(data.LastName);
		$("#FirstName").val(data.FirstName);
		$("#Message").html(data.Message);
	};

getJSON method will load Json data using HTTP Get request.  It takes in 3 parameters:

  • url or your controller action in this case
  • data (UserId for this example)
  • callback function that is called when the data is loaded. In the above example updateFields is called when the controllerAction returns  Json data.

We can also use post instead of getJSON if your action responds to POST requests. Then your call would look something like this, with everything else remaining same:

$.post(“PopulateDetails”, user, updateFields, ‘json’);

Now let us go ahead and look at our ControllerAction method:

public JsonResult PopulateDetails(UserModel model)
{
	UserResultModel userResultModel = new UserResultModel();
	if (String.IsNullOrEmpty(model.UserId))
	{
		userResultModel.Message = "UserId can not be blank";
		return Json(userResultModel);
	}

	User user = _userRepository.GetUser(model.UserId);

	if (user == null)
	{
		userResultModel.Message = String.Format("No UserId found for {0}", model.UserId);
		return Json(userResultModel);
	}

	userResultModel.LastName = user.LastName;
	userResultModel.FirstName = user.FirstName;
	userResultModel.Message = String.Empty; //success message is empty in this case

	return Json(userResultModel);
}

The above method would return a JsonResult that would be interpreted on the client side by the script that we wrote earlier with the help of jquery library.

This is as easy as it gets. Combination of jquery and JsonResult enables us to create applications that is AJAX enabled with minimal effort. You can get the source code for the application that is discussed above here.

About these ads

Written by shashankshetty

March 4, 2009 at 4:25 am

17 Responses

Subscribe to comments with RSS.

  1. […] from WebForms? Well, my friend and former colleague Shashank Shetty shows how it is done with ASP.NET MVC and jQuery in his inaugural blog post. Posted Mar 08 2009, 06:23 PM by Joshua Flanagan Filed under: jquery, […]

  2. Using JsonResult with jquery in ASP.net MVC « Shashank’s Blog…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

    DotNetShoutout

    March 8, 2009 at 11:42 pm

  3. […] to Vote[Del.icio.us] Using JsonResult with jquery in ASP.net MVC ” Shashank’s Blog (3/8/2009)Sunday, March 08, 2009 from […]

  4. […] Using JsonResult with jQuery in ASP.NET MVC (Shashank Shetty) […]

  5. Can you give any insight regarding parameters sent to the controller method?

    Some code I’m working on works fine when the second parameter of the getJSON method call is null. But when I attempt to pass in a value, it seems as if the controller method never even gets called.

    In my case, I just want to use an integer.

    Here’s sample of my code. The getJSON call looks like this:

    $.getJSON(“/News/ListNewsJson/”, null, ListNews_OnReturn);

    And the controller method is like this:

    public JsonResult ListNewsJson(int? id)
    {

    }

    By putting a breakpoint in the ListNewsJson method, I see that this method gets called when the data parameter of getJSON is null, but when I replace it with value, such as, say, 3:

    $.getJSON(“/News/ListNewsJson/”, 3, ListNews_OnReturn);

    … the controller method/breakpoint is never hit. Any idea why?

    Daniel

    March 18, 2009 at 6:42 pm

    • One thing to note here is that data in $.getJSON method is key/value pair, so instead of sending plain 3 you can try something like {“id” : 3}.

      shashankshetty

      March 19, 2009 at 2:41 am

  6. Thank!
    You save my time. It’s useful to build rich user interfaces with jQuery.

    Hoang Thinh

    January 4, 2010 at 6:14 pm

  7. i thing that you do something wrong $.getjson is easily hackable so $.post() is recommanded to send json.

    anirudha

    July 11, 2010 at 11:41 am

    • I agree. The post was written more than a year back for ASP.Net MVC 1.0. I haven’t had the chance to update the post. I appreciate you noticing. Thank you.

      shashankshetty

      July 18, 2010 at 10:00 pm

  8. Correction in my post…

    Shashank,
    In my project, I added this line after the $.post …

    $(“#Message”).html(“calling JSON…”);

    …to ensure it executed. It did, but my callback function is not getting executed. Can you explain how the data needs to be passed to the controller function? When you specify

    var user = {}
    user.UserId = …

    and the signature (UserModel model) in the controller method, this also has to be exactly the same as model used on the page, coorect?…

    Inherits=”System.Web.Mvc.ViewPage(SampleMvc.Models.UserModel)”

    Or can it be different? This seems to be the only difference I can find between your sample project and mine

    Barry Novak

    October 20, 2010 at 3:38 pm

    • Based on what you said, it should work. Did you try debugging using Firebug.

      shashankshetty

      October 21, 2010 at 4:11 pm

      • Shashank,
        Thanks for your quick reply. I installed Firefox/Firebug (great idea–even for a novice web developer like me, it was about time I started using it!).
        But I’m still not getting the results I expect. Here’s my javascript…

        var WebPageModel =
        { WEBPAGETITLE : $(‘#webpagetitle’).val(),
        WEBPAGETEXT : $(‘#webpagetext’).val()
        };
        $.post(“UpdateWebPage”, { WebPageModel : “model” }, RefreshAfterEdit, ‘json’);

        In Firebug Watch panel as I step through, I see values for the two attributes of the WebPageModel object. But in my controller method:

        public JsonResult UpdateWebPage(WebPageModel model)

        where I put a breakpoint, model’s properties are zero or null. The WebPageModel class is defined:

        namespace AnswerMe.Models
        {
        public class WebPageModel
        {
        public string WEBPAGETITLE { get; set; }
        public string WEBPAGETEXT { get; set; }
        }
        }

        Can you suggest what I’m doing wrong?

        Barry Novak

        October 22, 2010 at 2:08 pm

      • It looks fine Barry. Only thing I can think of is if you have [AcceptVerbs(HttpVerbs.Post)] on your action method and jquery post as
        $.post(“UpdateWebPage”, WebPageModel, RefreshAfterEdit, ‘json’);

        shashankshetty

        October 25, 2010 at 11:08 am

  9. Shashank,
    I found my problem. I had HTML tags in the text I was passing to the server. Probably a common beginner’s mistake. I’ll find some way to encode the text.
    Thanks for your help and quick replies!

    Barry Novak

    October 25, 2010 at 2:49 pm

  10. […] MVC : End to end Jquery, Another example using JsonResult object and a broader […]

  11. Greetings, Myself really enjoy coding with Ruby.Havent been
    using it a long time but learnt so much from website pages
    throughout the net. However, your website has assisted me quite a bit,
    and not to mentyion I say thank you for the understandable explanations and really easy to follow
    material on this webpage.

    Michael

    March 12, 2014 at 8:49 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: