Cascading dropdowns are returning undefined in mvc
I know this question is on a lot of others here. But here is my issue regarding the matter.
My Json Call in homecontroller:
public JsonResult GetBrand(int id) { List<String> resultdata = new List<String>(); //get some data via sql query using (SqlCommand command = new SqlCommand(query, sqlconn)) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { resultdata.Add(reader.GetString(0)); } } } return Json(resultdata, JsonRequestBehavior.AllowGet); }
My 2nd Dropdown’s code:
@Html.DropDownList("Brand", new SelectList(string.Empty, "", ""), "Please select", new { @class = "form-control" })
I also tried:
@Html.DropDownList("Brand", new SelectList(string.Empty, "div_id ", "material_name "), "Please select", new { @class = "form-control" })
And my script:
$(document).ready(function () { $("#category").change(function () { $.get("GetBrand", { id: $("#category").val() }, function (data) { console.log(data); $("#Brand").empty(); $.each(data, function (index, row) { console.log(row); $("#Brand").append("<option value='" + row.div_id + "'>" + row.material_name + "</option>") }); }); }) });
On Chrome’s F12 console, I can see this actual list of data I want returned in the dropdown and it is correct (via console.log(row);). However, in the dropdown itself, it shows undefined.
Does anyone have any suggestions to what I am missing?
Answer
This was my fix for anyone also missing something so simple:
while (reader.Read()) { items.Add(new SelectListItem { Value = Convert.ToString(Convert.ToInt32(reader["div_id"])), Text = reader["material_name"].ToString() }); }
Now it returns values.