I am needing to select values from a JSON, that is created based off a SQL Server database, and add them to a dropdown list as value seleciotns. I am using asp.net MVC. Everything seems to be working, excpet I can not figure out how to select "value" and "name" from my Json and use them. All I need help with is selecting those varibles and using them in the code.
This is my javascript function
$(function () {
$("#ddlDepartments").change(function () {
var selectedid = $('option:selected').val();
var ddlSubDepartments = $("#ddlSubDepartments"); //get the dropdownlist
if (selectedid > 0) {
$.ajax({
url: "/RecordEntries/PopulateddlSubDepartments",
data: {
id: selectedid
},
type: "Post",
dataType: "Json",
success: function (data) {
alert(data);
ddlSubDepartments.html("");
ddlSubDepartments.append($('<option></option>').val("").html("Please select a Sub Department"));
for (var i = 0; i < data.length; i++) {
ddlSubDepartments.append($('<option></option>').val(value[i]).html(name[i]));
}
},
error: function () {
alert('Failed to retrieve Sub Departments.');
}
});
}
});
});
And my JSON is like this, it can be edited to whatever format.
{"value":5,"name":"Sub Department 1"},{"value":8,"name":"Sub Department 2"}
EDIT: I'll add in my controller action that the jscript is calling at the beginning.
public ActionResult PopulateddlSubDepartments(int id)
{
var query = from d in _context.SubDepartments
where d.DepartmentId == id
select "{\"value\":" + d.SubDepartmentId + "," + "\"name\":\"" + d.SubDepartmentName + "\"}";
if (query == null)
ViewBag.SubDepartments = false;
else
ViewBag.SubDepartments = true;
return Json(query.ToList());
}