Dynamically populating a ListBoxFor based on a DropDownList selection

The name of the picture


Dynamically populating a ListBoxFor based on a DropDownList selection



(New to javascript, ajax and json.)
I have a DropDownList with categories of "news sections", and a listbox for the actual news items with the respective category.



Controller code for the dropdown list:


public ActionResult CreateModule() {
ModuleViewModel model ...
model.Sections = GetSectionCategories();

return View(model);
}

public List<NewsCategory> GetSectionCategories()
{
List<NewsCategory> Categories = new List<NewsCategory>();

foreach(var category in context.NewsCategory.Where(some condition)
{
Categories.Add(category);
}

return Categories;
}



User selects a category from dropdown list which triggers an ajax that retrieves items for the list box. Once that is complete, the function should populate the listbox on the page using the list of items it received via controller.



Html:


@Html.DropDownListFor(m => m.SectionCategoryId
, new SelectList(Model.Sections, "Id", "Title"))

@Html.ListBoxFor(m => m.SelectedItems, Model.ItemsList, new { id = "listBoxItems", @class = "chosen" })



Script:


$("#SectionCategoryId").change(function () {
$.ajax({
data: { model: ("name of the form").serializeArray, cid: $(this).val() },
url: "@Url.Action("EditSections","Module")",
success: function (result) {
},
error: function (data){
}
});

$("#listBoxItems").trigger("chosen:updated");
});



Controller:


public List<News> EditSections(ModuleDetailViewModel model, int cid)
{
List<News> list = new List<News>();
if(cid != 0)
{
list = context.News.Where(some condition).ToList();
}
else
{
list = context.News.Where(other condition).ToList();
}
return list;
}



Precisely, the ajax recieves a List as a result, that should be converted to an array, or parsed somehow so it can be used to populate the listbox. I've tried every solution I managed to find.



Examples tried:
First:


$("#SectionCategoryId").change(function () {
$.ajax({
data: { model: ("form name").serializeArray, cid: $(this).val() },
url: "@Url.Action("ReturnList","Module")",
success: function (result) {
var data = JSON.parse(result);
var i = 0; var append = '';
if ((data['result_data'].length > 0)) {
for (i = 0; i < json_data['result_data'].length; i++) {
var state = data['result_data'][i].Selected;
append += "<option value='" + data['result_data'][i].Value + "' slected='" + (state ? "selected" : "" ) + "'>" + data['result_data'][i].Text + "</option>";
}
$('#listBoxItems').html(append);
}
},
error: function (data){
}
});

$("#listBoxItems").trigger("chosen:updated");
});



Received no errors via console, but the function doesn't reach the method in the controller:


public JsonResult ReturnList(ModuleDetailViewModel model, int pid, int cid)
{
if(pid != 0 && cid == 0)
{
List<HtmlPage> pag = EditTheList(model, pid);
return Json(new { PagesList = pag });
}
else
{
List<News> sec = EditSections(model, cid);
return Json(new { ItemsList = sec });
}
}



Second, nothing happens after reaching the controller:


$("#SectionCategoryId").change(function () {
$.ajax({
data: { model: ("form name").serializeArray, cid: $(this).val() },
url: "/Module/EditSections",
success: function (result) {
var options = result;

for (var k = 0; k < options.length; k++)
{
$('#listBoxItems').html("");
$('#listBoxItems').append('<option value="' + options[k].Value + '" selected="' + (options[k].Selected ? "selected" : "") + '">' + options[k].Text + '</option>');
}
}
});
$(".chosen").chosen().change();
$(".chosen").trigger('listBoxItems_chosen:updated');
});



Also tried this solution with parsing the result as Json.



Third, also nothing:


$("#SectionCategoryId").change(function () {
$.ajax({
data: { model: ("form name").serializeArray, cid: $(this).val() },
url: "/Module/EditSections",
success: function (result) {
var options = ;
for (var i in result.data)
{
options.push(i);
}

for (var k = 0; k < options.length; k++)
{
$('#listBoxItems').html("");
$('#listBoxItems').append('<option value="' + result[i].Value + '" selected="' + (result[i].Selected ? "selected" : "") + '">' + result[i].Text + '</option>');
}
}
});
$(".chosen").chosen().change();
$(".chosen").trigger('listBoxItems_chosen:updated');
});



Important: none of the data is "hard-coded" or can be, and all data is retrieved from the database.









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Stripe::AuthenticationError No API key provided. Set your API key using “Stripe.api_key = ”

CRM reporting Extension - SSRS instance is blank

Keycloak server returning user_not_found error when user is already imported with LDAP