Watch videos with subtitles in your language, upload your videos, create your own subtitles! Click here to learn more on "how to Dotsub"

How Do I: Return JSON Formatted Data for an AJAX Call in an ASP.NET MVC Web Application?

0 (0 Likes / 0 Dislikes)
  • Embed Video

  • Embed normal player Copy to Clipboard
  • Embed a smaller player Copy to Clipboard
  • Advanced Embedding Options
  • Embed Video With Transcription

  • Embed with transcription beside video Copy to Clipboard
  • Embed with transcription below video Copy to Clipboard
  • Embed transcript

  • Embed transcript in:
    Copy to Clipboard
  • Invite a user to Dotsub
[Microsoft ASP.net] [www.ASP.net] [Chris Pels] Hi, this is Chris Pels. In this video we're going to learn a little bit about using JSON data in an ASP.net MVC website. We'll get started by creating a sample site. Let me go in here to new project. We're going to create it in VB. The sample download also has the C# version. To differentiate the two I'll just call this MvcApplicationVB and we'll put it in a folder for packaging up the samples. Now this is going to use the standard MVC template to create the project. As you may know if you've worked with MVC apps you have the option of creating a parallel unit test project for unit tests against the MVC site. For the demo here we're just going to bypass that step and not have the unit test project. So we'll get the standard template for a starter MVC website. In case you haven't seen that let me just fire it up here quickly and we'll take a look. It creates a very simple site with two pages. We've got a homepage and then it also will have an about page. There are the two pages. Now we're going to be focusing mostly on the data aspect of this, so we're really not going to do a whole lot— we'll do a little bit, but not a whole lot with this sample site. Now let's get started and take a look at the JSON data aspect of this MVC website. Where JSON data is really useful is if you're making AJAX calls back to your website. Let's set up a little page for customer information here and then we'll get into using the customer data in a JSON format. We'll add a few things to our sample site. Let's add a controller, and we'll just call this the CustomerController, and we need a page that corresponds to that controller so we'll go down into the views. We'll add a new folder and we'll call that customer," and inside of the customer folder let's add a new view. We're going to call this index, and that's going to match the index function over here in our controller. We'll just use the standard master for the site. So now we have our page and, while we're at it, let's go over here into the shared folder to the site master because the way this template works is it has these little menu items and that's how you see the tabs on the screen. We'll just copy and paste one of those in here, and we're going to alter the action link for our customer information so I'll just put "Customer" as the text to be displayed. We'll put "Index" because that's the function, and we'll just call this "customer." Now let's start up and take a look at our sample website to make sure we have our customer page operational. We'll fire it up, and there's our customer tab. Click on it and we should get—there we go. We get our customer page. Now we'll go back and look at the customer controller for adding the JSON functionality. Here in our customer controller we have an index function currently that maps over to the index view—Index,aspx. What we want to do is to create a second function and this will be what we call using AJAX to get the information for a single customer. So let's go in here and create a new function , and we'll call it GetCustomer. We need to return something called a JSON result and, as you can see in the tool kit, that says "Class used to send JSON content to the response." We'll select that as our return type. I'm going to show you how we get the customer information into JSON format momentarily here. What we'll do for our demo is create an instance of the customer class and manually populate those two properties that we have in the customer class in our model. In your own application it would likely be returning the customer from the database, passing an ID, but the basic process of getting it into JSON format will be identical to what we do here in this sample function. Let's dimension a local variable called customer as a— let's make a new customer, and what we do here with that customer, let's just set the property at CustomerName = "Microsoft" and the CustomerCity = "Redmond" and then, down here, all you have to do to get it—this instance of the customer class— into a JSON format—and we'll go to our return statement and we'll just go JSON, and there is a function called JSON. Let me just show you the different overrides for it. You can pass in data as an object. We're going to do that. We're going to pass in the instance of the customer class. You can also specify a content type and, in addition to that, the content encoding. All we need to do here is to return the customer object instance using this JSON function and then the call to this GetCustomer function will have as the return the customer object in JSON format. So now let's take a look at setting up a call to this function so that we can actually see the JSON data going back to the page and being displayed on the page. What we're going to do is we're going to have the customer page load in. When the page loads it we're going to have it do an AJAX call back to the customer function and return our customer information in JSON format. In order to do that we need to do a few little things here in our template site. First I'm going to go into the site master, and I am going to add a reference to some script. Let's use jQuery here to make our call to get the JSON-formatted customer. I'm going to add that script reference here in the site master so it will be available on all the pages that are based upon the master, and then let's go in here and let's add a ContentPlaceHolder—an ID. We'll call it "HeaderContent" and we're doing this because we need to be able to put some content in the header of our customer page. By adding this here to the template what we're going to get is the ability to have content inserted into the header from our page. We'll go back over here. Let's just save that. We'll go back over here to the index page and let's add another ASP content ID—we'll just call this "header"— and ContentPlaceHolder ID= "HeaderContent" Runat= "Server" and that should do it. So now what this gives us the ability to do is to put a <script> in here. In here we're going to put some JavaScript that is executed when the page starts. Let's just go up here into our <script>. We need the type equal to JavaScript. Let's add some script, and in jQuery what we need to do to run something when the page loads is to reference (document) .ready and inside there we're going to create a new function. Then we'll close out that function. So anything inside of this will run once the entire contents of the page is loaded. Let's just put a little test into here, and let's run the page and make sure we're getting all these pieces working before we add the code to do our AJAX call. So we'll fire up the page over at the site, and we'll go over to our customer page, and when we hit that customer page we should get the alert box that says test. We'll go over here and click on customer. The customer page loads and, indeed, we get our alert box, so we have the basic mechanism in place, and now let's add the AJAX call. Now in jQuery getting JSON data is really very simple. They have a built in function for it. We'll go getJSON—notice we're getting the intellisense for jQuery here because over here we have the vsdoc file in our scripts folder, and that comes in the template with ASP.net MVC so that should work automatically, so to speak, for you. Now there are three things that we need to pass. One is the URL, and what we want to do is say "Customers/GetCustomer" and that maps over here to our controller, and the controller is called "Customer." Let me just—it's not plural. Let me just get rid of that. The function that we have in our controller class remember is called the GetCustomer, right here. That is our first value, and then map data, as you can see with the intellisense that's key/value pairs of information that will be sent over to the server, and that, for instance, is where you could pass an ID here over inbound to the GetCustomer function to get a particular customer from the database. We're just going to pass in null and then we have a callback function here that executes once the JSN data has been retrieved from the server using the AJAX call. We'll just call this—let's call it inbound data and we'll close that out. Inside of this let's just—and what we'll do here is we'll put another alert box, and now the data that's inbound is really the customer. In fact, let's go over there just to make this a little more obvious and we'll call that inbound JSON object "customer." Now we can go (customer.CustomerName— now we're not getting the intellisense all the way back to the customer object on the server because it's just JSON data. So you do have to remember that. We'll close that out, and we just need another parenthesis right there. So now what should happen is when the page loads we're going to first get our test alert box, then we're going to have our call right here on lines 12 to 14. That's going to do our AJAX-based call to our GetCustomer function. It's going to come back and the alert box should display the name of the customer, which, if you may remember from our customer controller here, is Microsoft. Let's go ahead and start this up and check it out. We'll open up the MVC website, go over to our customer page, and click on that. Remember we should get two alert boxes here. First we get the alert box with test in it. Now we're going to make our AJAX call and get the JSON data, and there, indeed, is the customer name on the customer object from the server. Let's close this out. Let me show you just a couple more quick things. First I'm going to comment out this line here because we really don't need it, but I'll leave it there in the sample code in case you want to use that in your testing, and the other thing we can do here—it may be obvious, but it's worth pointing out— is we can put a break point right over—let's put it here on on line 15. Now let's set up our page in the debug mode, and we'll click on that customer tab again, and what should happen this time is we should hit that break point, even though we are running script on the client making an AJAX call through the jQuery library back to the server. Here we go. We'll click on the customer tab. It will open that and, indeed, we hit our break point here on the server. That just reinforces the fact that you can use debugging during your AJAX calls to make sure everything is occurring the way you would want them to or possibly to debug some problem that you're having. We'll just let that run through here and, indeed, there we get the customer name from our JSON call. This has been a simple example, but it really demonstrates all the basic pieces that you need in order to return JSON data via an AJAX call in your website. Let's just do a very quick review of what we did here to get this functioning. We used the customer as our sample in this demo. We created a customer controller. We created a customer view. Then we created a customer class which contains our data. The main thing in the customer controller here is that we created a new function that returns a JSON result, and then we retrieved—or in this case, created and populated our customer object and then used the JSON function to format that object as JSON when it's sent back in the response. We went over to our customer page, added a little jQuery code with the getJSON function. That calls to the GetCustomer function and returns our customer information. I guess another thing I should point out here is that we're getting a single customer as JSON data. This could just as easily be a collection of customer objects, and the JSON function over here in the controller will format that list of customer objects as well. So you have a variety of ways that you can use this JSON function. I encourage you to download the sample source code that comes with the video. As I mentioned in the beginning, we did it in Visual Basic here in the demo, but the samples also include C#. This is Chris Pels, thanks for watching this video on using JSON data in and ASP.net NMVC website. [Microsoft ASP.net] [www.ASP.net]

Video Details

Duration: 15 minutes and 48 seconds
Country: United States
Language: English
License: All rights reserved
Genre: None
Views: 6
Posted by: neudesicasp on Sep 16, 2013

In this video Chris Pels shows how to use the JsonResult and Json classes to return instances of classes as JSON formatted data. First, a sample MVC web application is created and a controller and associated view are added for customer information. Then a simple customer class is created as part of the data model. A GetCustomer() function is then added to the customer controller to retrieve data for a single customer in JSON format. Finally, script is added to the customer view that uses jQuery to make an AJAX call to GetCustomer() to retrieve the customer data in JSON format

Caption and Translate

    Sign In/Register for Dotsub to translate this video.