Reputation: 443
I'm trying to populate Json response from an Ajax call to a drop down and bind Name and UserID in a dropdown. Dropdown values all shows undefined. What I'm doing wrong here? Can you please help?
Dropdown DIV -
<div class="row form-group spacer">
<div class="col-md-12">
<div class="col-md-12">
@Html.Label("Recipients")
<select id="commentrecipients" class="dirtyignore" name="commentrecipients"></select>
</div>
</div>
</div>
Ajax Call -
$.ajax({
type: "GET",
url: "/Submission/SecurityGroupsUsersAccessRight",
data: {
id: 214
},
success: function (data) {
var s = '<option value="-1">Please Select a Recipient</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].UserID + '">' + data[i].Name + '</option>';
}
$("#commentrecipients").html(s);
}
});
Json Response -
data = "[{"SecurityGroupID":31,"SecurityGroupName":"Permission Testers","UserID":30,"Name":"Dawn Test'Neil"},{"SecurityGroupID":31,"SecurityGroupName":"Permission Testers","UserID":213,"Name":"Dawn 2 Bates"}]"
Upvotes: 0
Views: 1065
Reputation: 2121
You need to parse the JSON data to get the object and then loop it.
ajax({
type: "GET",
url: "/Submission/SecurityGroupsUsersAccessRight",
data: {
id: 214
},
success: function (data) {
let response = JSON.parse(data);
var s = '<option value="-1">Please Select a Recipient</option>';
for (var i = 0; i < response.length; i++) {
s += '<option value="' + response[i].UserID + '">' + response[i].Name + '</option>';
}
$("#commentrecipients").html(s);
}
});
Upvotes: 1
Reputation: 348
$.ajax({
type: "GET",
url: "/Submission/SecurityGroupsUsersAccessRight",
data: {
id: 214
},
dataType: "json",
success: function (data) {
$.each(data.d, function (i, val) {
var s = '<option value="-1">Please Select a Recipient</option>';
s += '<option value="' + val.UserID + '">' + val.Name + '</option>';
}
$("#commentrecipients").html(s);
}
});
Upvotes: 0
Reputation: 291
Please try using the camel case property name:-
s += '<option value="' + data[i].userID + '">' + data[i].name + '</option>';
Upvotes: 0
Reputation: 69
Try adding dataType: "json" and remove the "data:" ... something like this:
$.ajax({
type: "GET",
url: "/Submission/SecurityGroupsUsersAccessRight",
dataType: "JSON",
success: function (data) {
var s = '<option value="-1">Please Select a Recipient</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].UserID + '">' + data[i].Name + '</option>';
}
$("#commentrecipients").html(s);
}
});
Upvotes: 0