Updating a dropdown using jquery from json

I have a list that I need to populate using a collection of JSON objects. Here is what my action returns:

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 came up with for my javascript compiled 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 does not work and does not give any errors. What is the best practice for this kind of thing?

+4
source share
2 answers

I was wondering what you are trying to achieve in the following lines of code,

 var option = new Option(optionData.Text, optionData.Value); selectList.add(option, null); 

Are you trying to create an option and then add it to select ? if yes, do it like this, use .append()

 selectList.append(option); 

with this, I still assume that new Option(optionData.Text, optionData.Value); creates a new option , in jQuery it will look like var option = $('<option>').text(optionData.Text).val(optionData.Value);


added notes for .add() ,

 var selectList = $("#subCategories"); // creates jQuery object selectList. selectList.add(option, null); // selectList is jQuery object, // so when you call .add(), you're calling jQuery `add()`. 

The workaround is

 selectList[0].add(option, null); // you can use [0] to convert it into DOM object. 

difference between:

+6
source

JQuery fails if it does not like the JSON data returned from the server. Point your browser to / Admin / Product / GetProductCategories and look at the result. Make sure it has no html tags and make sure that there are double quotes around the key names.

+1
source

All Articles