I have 2 cascade dropdowns in an editortemplates view. When I open the view for the first time and the editortemplate is loaded the data in the dropdowns load with no problems. However when clicking in a button that will repeat this editortemplate several times in my view the dropdowns data don't load. I have used routemapping for the cascade dropdowns and the button is calling a jquery. What can be wrong here?
This is the code for the dropdowns:
For the editortemplates view:
<script type="text/jscript">
$(function () {
$.getJSON("/Budget/Categories/List/", function (data) {
var items = "<option value='0'>Select a Category</option>";
$.each(data, function (i, category) {
items += "<option value='" + category.Value + "'>" + category.Text + "</option>";
});
$("#Category").html(items);
});
$("#Category").change(function () {
$.getJSON("/Budget/SubCategories/List/" + $("#Category > option:selected").attr("value"), function (data) {
var items = "<option value='0'>Select a SubCategory</option>"; ;
$.each(data, function (i, subcat) {
items += "<option value='" + subcat.Value + "'>" + subcat.Text + "</option>";
});
$("#SubCategory").html(items);
})
});
});
</script>
<label for="Category">Categories</label>
<select id="Category" name="Category" style = "width:150px"></select>
<label for="SubCategory">SubCategories</label>
<select id="SubCategory" name="SubCategory" style = "width:150px"></select>
For the controller:
[Authorize]
[HttpGet]
public ActionResult GetCategories()
{
IQueryable categories = _db.categories;
if (HttpContext.Request.IsAjaxRequest())
{
return Json(new SelectList(categories, "idCategory", "CategoryName"), JsonRequestBehavior.AllowGet);
}
return View(categories);
}
[Authorize]
[HttpGet]
public ActionResult GetSubCategories(int idCategory)
{
IQueryable subcategories = _db.subcategories.Where(c => c.idCategory == idCategory);
if (HttpContext.Request.IsAjaxRequest())
{
return Json(new SelectList(subcategories, "idsubCategory", "SubCategoryName"), JsonRequestBehavior.AllowGet);
}
return View(subcategories);
}
For the routeconfig:
routes.MapRoute("GetCat", "Budget/Categories/List/",
new { controller = "Budget", action = "GetCategories" });
routes.MapRoute("GetSubCat", "Budget/SubCategories/List/{idCategory}",
new { controller = "Budget", action = "GetSubCategories", idCategory = "" });
And this is the code for the button:
For the view:
<script type="text/jscript">
jQuery(document).ready(function ($) {
$('#add-bdetail').on('click', function () {
jQuery.get('/Budget/AddBudgetDetail').done(function (html) {
$('#bdetail-list').append(html);
});
});
});
</script>
<div> <input type="button" id="add-bdetail" value="Add row" /></div>
For the controller:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult AddBudgetDetail()
{
return View(new List<budgetdetail>() { new budgetdetail() });
}