Hi guys,
I have problem with Cascading dropdown list. After selecting any category, I need to get relevant subcategories in the second dropdown. Seems easy, but doesn't work with SelectList class which I used. After selecting any category, seems it doen't recognize
Id, and no subcategory comes to select.
Controller
[HttpGet]
public async Task<IActionResult> Postadd()
{
AdminPostModel postModel = new AdminPostModel();
postModel.Categories = await _offerDbContext.Categories.ToListAsync();
ViewBag.Categories = postModel.Categories;
return View(postModel);
}
public JsonResult getSubList(int Id)
{
List<Subcategory> list = new List<Subcategory>();
list =_offerDbContext.Subcategories.Where(a => a.CategoryId == Id).ToList();
return Json(new SelectList(list, "Id", "Name"));
}
View
@model Foroffer.Models.ViewModels.AdminPostModel
@{
Layout = "AdminLayout";
}<form method="post" asp-action="Postadd" asp-controller="Post" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly"></div>
<label asp-for="Post.Subcategory.Category.Name">Category</label>
<select id="CatId" name="CatList" asp-for="Category.Id" asp-items ="@(new SelectList(ViewBag.Categories, "Id", "Name"))" >
</select>
<br />
<label asp-for="Post.Subcategory.Name">Subcategory</label>
<select id="SubId" name="SubList" asp-for="Post.SubcategoryId" asp-items="@(new SelectList(String.Empty, "Id", "Name"))">
<option value="">Select Subcategory</option>
</select>
<br>
<button class="push" type="submit">Create</button>
</form>
<script>
$(document).ready(function () {
$("#CatId").on("change", function () {
$list = $("#SubId");
$.ajax({
url: "/getSubList",
type: "GET",
data: { id: $("#CatId").val() }, //id of the state which is used to extract cities
traditional: true,
success: function (result) {
$list.empty();
$.each(result, function (i, item) {
$list.append('<option value="' + item["Id"] + '"> ' + item["Name"] + ' </option>');
});
},
error: function () {
alert("Something went wrong call the police");
}
});
});
});
</script>
Models
public class Category
{
public Category()
{
Subcategories = new HashSet<Subcategory>();
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
public ICollection<Subcategory> Subcategories { get; set; }
public string Action { get; set; }
public string Controller { get; set; }
}
public class Subcategory
{
public Subcategory()
{
Posts = new HashSet<Post>();
}
[Key]
public int Id { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
public int CategoryId { get; set; }
public ICollection<Post> Posts { get; set; }
public string Action { get; set; }
public string Controller { get; set; }
public ICollection<CompanySubcategory> CompanySubcategories { get; set; }
}
Please, help ASAP