views:

115

answers:

3

I am using asp.net mvc with jquery... I have made a json call to a controller method and it returns json object [Object object] for me. I dont want that instead i want to get the json string... Any suggestion...

$(document).ready(function() {
        $.getJSON('Materials/GetMaterials', null, function(data) {
            alert(data);
        });
    });

I gave alert(data.d); and it is undefined

  public JsonResult GetMaterials()
    {
        var materials = consRepository.FindAllMaterials().AsQueryable();
        return Json(materials);
    }
A: 

getJSON will return a json object. If that isn't what you want you shouldn't use it. You can use $.ajax instead and set the content type to text/plain and you will receive the data as a string. I can't, however, see any reason you would want to work with a string instead of a object.

You can optionally use the JSON.stringify method from the json2 library to turn a object into a string.

Mattias Jakobsson
@Mattias Ok how can i iterate through json object... Consider 10rows containing `UserName` and `EmailId`.... I want iterate these object with `<td>data.Username</td>` and `<td>data.EmailId</td>`
Pandiya Chendur
@Mattias Is this possible?
Pandiya Chendur
@Pandiya Chendur, of course that is possible. You have a for loop in javascript you can use. jQuery has a each method that loops over a collection.
Mattias Jakobsson
@Mattias thanks i just posted my answer..
Pandiya Chendur
+1  A: 

Just found the answer,

$(document).ready(function() {
        $.getJSON('Materials/GetMaterials', null, function(data) {

        $.each(data , function(index,d) {
            alert(d.Id)
        });

        });
    });
Pandiya Chendur
A: 

Try using console.log (+ use firebug or web inspector) instead of alert(). You'll be able to expand the returned json object's structure and determine how to access the data you're after.

Ben Rowe
@Ben i got the answer...
Pandiya Chendur