I've implemented my cascading dropdown list with MVC3 almost exactly as explained in
Easiest way to create a cascade dropdown in ASP.NET MVC 3 with C#
My view had that
<script type="text/javascript">
$(function () {
$('#CategoryID').change(function () {
var selectedCategoryId = $(this).val();
$.getJSON('@Url.Action("SelectCategory")', { categoryid: selectedCategoryId }, function (subcategories) {
var subsSelect = $('#SubCategoryID');
subsSelect.empty();
$.each(subcategories, function (index, subcat) {
subsSelect.append(
$('<option/>')
.attr('value', subcat.SubCategoryID)
.text(subcat.SubCategoryName)
);
});
});
});
});
</script>
My controller had that
public ActionResult SelectCategory(int categoryid)
{
var subs = db.SubCategories.Where(s => s.CategoryID == categoryid).ToList();
return Json(subs, JsonRequestBehavior.AllowGet);
}
And that did not work.
However, it worked when I modified the controller the following way:
public class JsonSubCat
{
public int SubCategoryID { get; set; }
public string SubCategoryName { get; set; }
}
public ActionResult SelectCategory(int categoryid)
{
var subs = db.SubCategories.Where(s => s.CategoryID == categoryid).ToList();
var testsubs = new List<JsonSubCat>();
foreach (var sub in subs)
{
testsubs.Add(new JsonSubCat() { SubCategoryID = sub.SubCategoryID, SubCategoryName = sub.SubCategoryName });
}
return Json(testsubs, JsonRequestBehavior.AllowGet);
}
Looks like a question of converting my entities that I obtain from data source to proper format. What would be the correct way to implement this?