How to retrieve json data using jQuery and Json.NET?

I see this code sample in "Serializing and Deserializing Json | Serializing Collections" at http://james.newtonking.com/projects/json/help/:

Product p1 = new Product
{
  Name = "Product 1",
  Price = 99.95m,
  ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
};
Product p2 = new Product
{
  Name = "Product 2",
  Price = 12.50m,
  ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
};

List<Product> products = new List<Product>();
products.Add(p1);
products.Add(p2);

string json = JsonConvert.SerializeObject(products, Formatting.Indented);
//[
//  {
//    "Name": "Product 1",
//    "ExpiryDate": "2000-12-29T00:00Z",
//    "Price": 99.95,
//    "Sizes": null
//  },
//  {
//    "Name": "Product 2",
//    "ExpiryDate": "2009-07-31T00:00Z",
//    "Price": 12.50,
//    "Sizes": null
//  }
//]

So far so good; but how would this output be retrieved from jQuery? Would it be possible to have a file named JsonizedProducts.cshtml with:

@{
    return GetProductsAsJson(); // returns the string named "json" above
}

...and use jQuery such as (pseudocode):

$.getJson('\JsonizedProducts') {
    // loop through the json, building html with injected product values
}

? Or...?

UPDATE

I've found lots of examples for the client-side jQuery code necessary to do this; it's the server-side aspect that I'm missing. If I were to call .getJson(path, data, callback) with something like .getJSON("\Bla\Blee.js", someVal, someFunc), how would Blee.js pass back the JSON data? What is the responsibility of the file being called diesbzg?

UPDATE 2

Is this the/a way I can do it (getPlatypus() and getWombat() are methods in other classes that return a List<>):

// This code is in the file that .getJson() calls; the data (args) .getJson calls has "mammalRequested" Using the Web.Helpers Json helper
string jsonResult;
if (mammalRequested == "Platypus") {
    jsonResult = Json.Encode(getPlatypus); 
}
else if (mammalRequested == "Wombat") {
    jsonResult = Json.Encode(getWombat); 
}
Response.Write(jsonResult);

?

UPDATE 3

This isn't an answer to my question, since I mention Json.NET, but it's quite possibly the best solution: I know there's a way to pass back jsonized data from C# (Brind's book shows how on pages 168-170), but probably the most sensible (least muss and fuss) is to simply call a .js file that contains json data like so:

$.getJson('someFile.js', 'someArg', someCallbackFunction);

And the easiest way (for me) to create a Json file? First, create a csv file, than use the CSV2Json converter, such as from http://www.convertcsv.com/csv-to-json.htm.

Then, of course, use .each(data) to loop through the json records and "have at them."

Upvotes: 0

Views: 551

Answers (1)

dav83
dav83

Reputation: 322

I'm guessing you're using the MVC framework since you're talking about .cshtml files. If so, make a method in your controller like this:

[HttpGet]
public JsonResult GetProductsAsJson()
{
    List<Product> products = repository.GetProducts(); //or whatever code generates the list
    return Json(products, JsonRequestBehaviour.AllowGet);
}

Then in your javascript, just do what you did above! The url will be the method name and controller name as usual. If you're putting the javascript in the .chstml page you can use Url.Action("GetProductsAsJson", "MyController') to render the url of the method.

EDIT:

Ok, based on comments, try this:

Create a namespace and class in a .cs file in your project:

namespace MyThings
{
    public class DbRepository
    { 
         public static string GetProductsJSON()
         {
               //code to create json string
               return json;
         }
    }
}

Then in your .cshtml file add a using directive at the top of the page:

@using MyThings

And call the method in a razor block to set a variable, then use razor to loop through:

@{ 
    List<Products> prods = DbRepository.GetProductsJSON();
 }

 <ul>
     @foreach (var prod in prods)
      {
           <li>@prod.Name</li>
      }
 </ul>

Not a web pages expert but I think this will work.

Good luck!

Upvotes: 1

Related Questions