I am populating two Dropdown lists (Category and SubCategory) in my view.
I am doing that thru my controller, and i want the Dropdown of SubCategory to be populated depending on the selected item from Category.
So i have made the Controller and View, but i need now Ajax script to make this work. Can anyone help me with suggestions.
Controller:
[HttpGet]
public ActionResult Edit(int id)
{
EntryViewModel model = (from subcat in dc.SubCategory
join en in dc.Entry on subcat.SubCategoryId equals en.SubCategoryId
join cat in dc.Category on subcat.CategoryId equals cat.Id
where en.Id == id
select new EntryViewModel {
Id = en.Id,
Title = en.Title,
Username = en.Username,
Password = en.Password,
Url = en.Url,
Description = en.Description,
CategoryId = cat.Id,
CategoryName = cat.Name,
SubCategoryId = subcat.SubCategoryId,
SubCategoryName = subcat.Name
}).First();
string selectedCat = (from cat in dc.Category
join en in dc.SubCategory on cat.Id equals en.SubCategoryId
where cat.Id == en.SubCategoryId
select cat.Name).First();
ViewBag.SubjectNameCat = new SelectList(dc.Category, "Id", "Name");
return View(model);
}
public JsonResult SubCategories(int id)
{
string selected = (from cat in dc.SubCategory
join en in dc.Entry on cat.SubCategoryId equals en.SubCategoryId
where en.Id == id
select cat.Name).First();
return Json(new SelectList(selected.ToArray(), "SubCategoryId", "Name"), JsonRequestBehavior.AllowGet);
}
View:
<div class="editor-label">
Category
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.CategoryId
(IEnumerable<SelectListItem>)ViewBag.SubjectNameCat,
new { @class = "form-control" })
</div>