0

It's been a while since I've used jQuery and I'm having difficulty getting the value from the JSON that is being returned from the server.

C# method

        [HttpGet]
        public JsonResult AjaxGetSingleNewsItem(int Id)
        {
            string json = JsonConvert.SerializeObject(news.GetNewsItems().Where(d => d.UniqueId == Id), formatting: Formatting.Indented);
            var v = JArray.Parse(json);

            var model = (from p in v
                         select new ModelNewsWidget()
                         {
                             Id = p["UniqueId"].ToString(),
                             ImagePath = _imagePath,
                             NewsItemImageReference = p["NewsItemImageReference"].ToString(),
                             Title = p["Title"].ToString().Substring(0, 14),
                             SubTitle = p["Title"].ToString().Substring(15),
                             AddedOn = Convert.ToDateTime(p["AddedOn"].ToString()).ToShortDateString(),
                             NewsRef = p["BodyText"].ToString().Substring(5, 13),
                             BodyText = p["BodyText"].ToString().Replace(System.Environment.NewLine, string.Empty)
                         }).ToList();

            json = JsonConvert.SerializeObject(model);

            return new JsonResult()
            {
                Data = json,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                MaxJsonLength = Int32.MaxValue
            };
        }

function getSingleNewsItem(id) {
        var url = '@Url.Action("AjaxGetSingleNewsItem", "News")';
        var data = {
            id: id
        };

        $.ajax({
                type: "GET",
                url: url,
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                success: function (data) {
                    alert(data[0].NewsRef);
                },
                error: function (data) {
                }
            });
        };

This is undefined:

alert(data[0].NewsRef);

This is my JSON

[
    {
        "ImagePath": "http://vmwebapps.rhs.net/AMT/AMT_Files/HortifactsAttachmentsTest/NewsItems/",
        "Id": "6",
        "NewsItemImageReference": "http://vmwebapps.rhs.net/AMT/AMT_Files/HortifactsAttachmentsTest/NewsItems/9750cf57-bc14-4205-9e6c-83c8406f3f82.jpg",
        "Title": "Tree fungus ID",
        "SubTitle": " Inonotus dryadeus",
        "AddedOn": "16/09/2013",
        "NewsRef": "204201/252874",
        "BodyText": "Ref: 204201/252874The fruiting bodies are those of a fungus called Inonotus dryadeus. Oak is the most common host of this fungus, which can often cause decay of the inner parts of the root system and the base of the trunk.Whilst the fungus can cause extensive decay, the effect on the tree itself can be very variable. Some trees will survive for many years or even indefinitely - although the central roots and wood may decay the hollow tree remains alive and standing on 'stilts' of buttress roots. However, if the decay also affects these roots then there is a risk of the tree falling. In a case such as this we would always recommend having the tree examined in situ by an arboricultural consultant, particularly if there is any risk of injury or damage to property should the tree fall. The consultant will be able to check the location and extent of the decay, and recommend any appropriate remedial action (such as crown reduction).The link below takes you to our web profile on bracket fungi. This does not mention Inonotus dryadeus specifically, but gives the contact details for the Arboricultural Association who will be able to provide you with a list of suitably-qualified consultants operating in your area. http://apps.rhs.org.uk/advicesearch/Profile.aspx?pid=98I hope this information is helpful.Yours sincerely, John ScracePlant Pathologist"
    }
]

Results of firebug:

console.log(data);
console.log(data.NewsRef);
console.log(data[0].NewsRef);

[{"ImagePath":"http://vmwebapps.rhs.net/AMT/AMT_Files/HortifactsAttachmentsTest/NewsItems/","Id":"12","NewsItemImageReference":"http://vmwebapps.rhs.net/AMT/AMT_Files/HortifactsAttachmentsTest/NewsItems/7bc9ca37-d3da-4972-9f19-be3f245eb905.jpg","Title":"Large Yellow U","SubTitle":"derwing","AddedOn":"25/09/2013","NewsRef":" yellow under","BodyText":"Large yellow underwing - sent via twitter - Anna says several already submitted to our entomologists this week: https://twitter.com/HannahBellaaaa/status/382814806886973440/photo/1Massed eggs diagnostic: http://ukmoths.org.uk/show.php?bf=2107"}] (index):471

undefined (index):472
undefined 

I've been banging my head against the wall for a while with this, so any help would be appreciated.

7
  • console.log(data) and also check with firebug for response ? Commented Nov 12, 2014 at 16:39
  • Are you sure the parameters are being sent correctly? AFAIK, $.ajax doesn't know how to send JSON parameters, so you need to use data: JSON.stringify(data). Commented Nov 12, 2014 at 16:40
  • @Barmar My breakpoint is hit in my C# method and I can see the data being returned. I don't think this is the problem. Commented Nov 12, 2014 at 16:46
  • FYI, since you are actually not sending JSON, you should not set contentType: "application/json; charset=utf-8". Also, your C# is quite clowny. Why are you converting data to JSON (string json = JsonConvert.SerializeObject(...);), if you immediately parse it again in the next line (var v = JArray.Parse(json);)? Commented Nov 12, 2014 at 16:55
  • What does console.log(data[0]) show? Commented Nov 12, 2014 at 17:03

1 Answer 1

1

You need to parse the JSON data before you can access it.

try the following:

success: function(data){ 
var parsedData =  $.parseJSON(data);
alert(parsedData[0].NewsRef);
}
Sign up to request clarification or add additional context in comments.

5 Comments

You shouldn't need to do this in you're passing dataType: 'json' in your $.ajax call...
@MadDawgTom - your code works, but I don't understand why I have to parse it when I am returning JSON?
I think it is because the information you are passing INTO the request is not json
@nickgowdy: Well, in general JSON is just a textual data format (like XML). You have to convert the JSON data to JavaScript objects / arrays (that's the "parsing" process). However, since you specified dataType: 'json', jQuery should be doing this for you.
@MadDawgTom: That has nothing to do with it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.