Hi
I have this web page with multiple categories. I have build the table with a self reference table in entity framework, so the user can create categories with multiple children.
I want an dropdown list with categories and when you click on the dropdown menu, I get the value and send the value with ajax to the controller and check if this category have children and populate this in an new dropdown list.
I have done this function, but how do I make a function that populate a new dropdownlist everytime when I click in the dropdown list with out hardcode the dropdown list??
This is my view code :
@Html.DropDownList("CategoryId", ViewBag.CategoryId as SelectList, "Select a Category", new { id = "CategoryId", @class = "form-control" })<br />
@Html.DropDownList("Subcategory", new SelectList(string.Empty, "Value", "Text"), "Please select a Subcategory", new { @class = "form-control" })
The ajax call in the view :
jQuery(document).ready(function ($) {
$("#CategoryId").change(function () {
var id = $(this).find(":selected").val()
var catId = { "catId": id }
$("#Subcategory").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("CategoryList", "Manage")',
data: JSON.stringify(catId),
contentType: 'application/json; charset-utf-8',
success: updateDropdown
});
});
});
var updateDropdown = function (subcategories) {
if (subcategories.length == 0) {
console.log("NO DATA!")
}
else {
var ddl = $('#Subcategory');
$.each(subcategories, function (index, item) {
$(document.createElement('option'))
.attr('value', this.Id)
.text(item.Text)
.appendTo(ddl);
});
}
};
[HttpPost]
public JsonResult CategoryList(int catId)
{
var subcategories = (from s in db.Categories where s.ParentCategoryId == catId select new SelectListItem {
Text = s.Name, Value = s.ParentCategoryId.ToString()
});
return Json(subcategories, JsonRequestBehavior.AllowGet);
}
Hope someone could get me in the right direction