I'm trying to get a jSON response using jQuery 1.5.1 with mvc3 and the javascript is silently crashing out. Debugging the server side code i'm definitely passing a populated list to the response.
Some further information in regards to the comments.
The response returned in firebug is thus:
[{"LocationId":"ASXX0413","LocationName":"Albany, Australia"}]
and firebug also recognises it as a jSON object.
My Javascript:
weatherEvents: function () {
jQuery("a#getweather").click(function (event) {
event.preventDefault;
var query = jQuery("#Farm_Weather").val();
if (query === "") {
return;
}
jQuery.getJSON("/Farm/Weather", { location: query }, function (data) {
var items = [];
jQuery.each(data, function (key, val) {
items.push("<li>" + val.LocationId + " : " + val.LocationName + "</li>");
});
jQuery("<ul/>", {
"class": "weather-location-list",
html: items.join("")
}).appendTo("div.weatherdiv");
});
});
}
My server side code:
[HttpGet]
public JsonResult Weather(string location)
{
string requestUrl = string.Format(
"http://xoap.weather.com/search/search?where={0}",
HttpUtility.UrlEncode(location.Trim()));
XmlDocument xmlDoc = new XmlDocument();
XmlNodeList nodeList = null;
// Place a call to Weather.com and search for this location
xmlDoc.Load(requestUrl);
nodeList = xmlDoc.SelectNodes("/search/loc");
// Cast our nodelist and get a new anonymous type.
var jsonWeather = nodeList.Cast<XmlElement>()
.Select(x => new
{
LocationId = x.GetAttribute("id"),
LocationName = x.InnerText
});
return Json(jsonWeather.ToList(), JsonRequestBehavior.AllowGet);
}