I have a list that I need to fill using a JSON collection of object. Here is what my action is returning:
public ActionResult GetProductCategories()
{
var categories = _entities.ProductCategories.ToList();
var result = new List<SelectListItem>();
foreach (var category in categories)
{
result.Add(new SelectListItem {Text = category.CategoryName, Value = category.CategoryId.ToString()});
}
return Json(result, JsonRequestBehavior.AllowGet);
}
This is what I’ve come up with for my javascript, gathered from various sources:
function loadCategories() {
$.getJSON("/Admin/Product/GetProductCategories", null, function (data) {
var selectList = $("#subCategories");
$.each(data, function(index, optionData)
{
var option = new Option(optionData.Text, optionData.Value);
selectList.add(option, null);
});
});
}
But it doesn’t appear to be working, and isn’t giving any errors. Whats the best practice for this sort of thing?
I was wondering what are you trying to achieve in this next lines of codes,
are you trying to create an
optionthen add it onselect? if so, do it like this, use.append()with that, I’m still assuming
new Option(optionData.Text, optionData.Value);is creating a newoption, in jQuery it would be like thisvar option = $('<option>').text(optionData.Text).val(optionData.Value);added notes for
.add(),a workaround is this,
difference between:
selectobject’s .add()