0

I cannot seem to figure out why my $.get call returns one single object with a string containing my elements, when my controller returns a list of objects.

Controller:

public JsonResult GetInitialTags(int id)
{
    Model = new UnitDetailsModel(UnitClient.GetUnit(id));
    foreach (var tag in Model.ViewUnitContract.Tags)
    {
        Model.TagsSelected.Add(tag);
    }

    var result = Model.TagsSelected.Select(a => new
        {
            id = a.Id,
            text = a.Name
        });

    return Json(result, JsonRequestBehavior.AllowGet);
}

This returns an array of two objects ([0], [1]). But, when I do my ajax call from view, like this:

var data = $.get('@Url.Action("GetInitialTags", "UnitDetails", new { id = Model.ViewUnitContract.Id })');

.. it returns one single object with a property responseText that contains my elements like this:

responseText: "[{"id":27,"text":"Norway"},{"id":28,"text":"Sweden"}]"

Any help would be appreciated! :)

1
  • It's returning an array of objects, which is the correct behaviour. What are you expecting as a response? Commented Oct 28, 2013 at 9:00

2 Answers 2

1

The $.get function doesn't return the data, it returns a jqXHR object, which is an extended version of the standard XMLHttpRequest object, which has multiple properties, including responseText.

You can get the deserialized data via the argument to the success callback:

$.get(
    '@Url.Action("GetInitialTags", "UnitDetails", new { id = Model.ViewUnitContract.Id })',
    function(data) {
    // Use `data` here
});

...or the argument to the done function on the returned jqXHR object, which is also a Promise.

$.get(
    '@Url.Action("GetInitialTags", "UnitDetails", new { id = Model.ViewUnitContract.Id })'
).done(function(data) {
    // Use `data` here
});

In both of the above, provided the server sent the response with the correct MIME type, data will be an array of objects.

Sign up to request clarification or add additional context in comments.

Comments

0

[{"id":27,"text":"Norway"},{"id":28,"text":"Sweden"}]

this is array of object...

anyways you can get the values inside get callback

 $.get('@Url.Action("GetInitialTags", "UnitDetails", new { id = Model.ViewUnitContract.Id })',function(data){
     var result=JSON.parse(data);
     alret(result[0].id);
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.