I am having issues iterating through the Object returned by the controller in C# MVC framework in my AJAX script.
Ajax script:
function getRName(obj) {
$.ajax({
url: 'resourceNamePopup',
method: 'post',
data: { "search": obj.value },
dataType: 'json',
success: function (data) {
alert('success');
$.each(data.items, function (items) {
alert(items.displayName);
});
}
});
}
C# Action:
public ActionResult resourceNamePopup(string search)
{
List<ResourceName> rnList = new List<ResourceName>();
rnList = getResourceName(search);
return Json(rnList );
}
I get this error now
Unhandled exception at line 645, column 4 in http://localhost:52273/Scripts/jquery-1.10.2.js
0x800a138f - JavaScript runtime error: Unable to get property 'length' of undefined or null reference
The obj
seems a pointless wrapper round what is just a single list. You only ever add one item to obj
, so it doesn't really do anything useful to have that as a list. just return the rnList
directly instead. And then in the JS just loop directly over data
. Also the fact you return a list of Object, which has no properties, means none of your properties get serialised into JSON, because it uses the type of the object being serialised to decide what to include in the JSON.
This should work better, and is simpler:
C#
public ActionResult resourceNamePopup(string search)
{
List<ResourceName> rnList = getResourceName(search);
return Json(rnList);
}
JS
function getRName(obj) {
$.ajax({
url: 'resourceNamePopup',
method: 'post',
data: { "search": obj.value },
dataType: 'json',
success: function (data) {
alert('success');
if (data != null || data.length == 0) {
$.each(data, function (index, item) {
alert(item.displayName);
});
}
else { alert("No results"); }
}
});
}
I want to point out two problems
You don't need to add into List<object>
$.each(data.items, function (items)
part is not correct
You need to return rnList
instead (from method resourceNamePopup()
[Also please make method and property names start with uppercase]).
and inside AJAX response use this:
function getRName(obj) {
$.ajax({
url: 'resourceNamePopup',
method: 'post',
data: { "search": obj.value },
dataType: 'json',
success: function (data) {
alert('success');
$.each(data, function (i) {
alert(data[i].displayName);
});
}
});
}
User contributions licensed under CC BY-SA 3.0