简体   繁体   中英

How to make Cascading dropdown in asp.net core mvc?

I was tried earlier but can't get success in that.

Can anyone tell me with example?

You could refer to the following steps to create a Cascading dropdown in asp.net core MVC.

  1. Create models withrelationships :

     public class Category { public int Id { get; set; } [Required] [Display(Name = "Category Name")] public string CategoryName { get; set; } public ICollection<SubCategory> SubCategories { get; set; } } public class SubCategory { public int Id { get; set; } [Required] [Display(Name = "SubCategory Name")] public string SubCategoryName { get; set; } public int CategoryID { get; set; } public Category Category { get; set; } }
  2. Then using EF core migration to create the related tables in the database, or create a service to set the initial data. Here I create a service:

     public interface IRepository { List<Category> GetCategories(); } public class Repository: IRepository { private readonly ApplicationDbContext db; public Repository(ApplicationDbContext context) { db = context; } //you can also query the database and get the data. public List<Category> GetCategories() { List<Category> categories = new List<Category>() { new Category(){ Id=101, CategoryName="Category 1", SubCategories= new List<SubCategory>(){ new SubCategory(){ Id=1001, SubCategoryName="SubCategory 1.1"}, new SubCategory(){ Id=1002, SubCategoryName="SubCategory 1.2"}, new SubCategory(){ Id=1003, SubCategoryName="SubCategory 1.3"}, } }, new Category(){ Id=102, CategoryName="Category 2", SubCategories= new List<SubCategory>(){ new SubCategory(){ Id=1001, SubCategoryName="SubCategory 2.1"}, new SubCategory(){ Id=1002, SubCategoryName="SubCategory 2.2"}, new SubCategory(){ Id=1003, SubCategoryName="SubCategory 2.3"}, } }, new Category(){ Id=103, CategoryName="Category 3", SubCategories= new List<SubCategory>(){ new SubCategory(){ Id=1001, SubCategoryName="SubCategory 3.1"}, new SubCategory(){ Id=1002, SubCategoryName="SubCategory 3.2"}, new SubCategory(){ Id=1003, SubCategoryName="SubCategory 3.3"}, } }, }; return categories; } }
  3. Register the service in Startup.ConfigureServices method:

     services.AddTransient<IRepository, Repository>();
  4. Then, in the MVC controller, using the following code to get the category and subcategory:

     public class HomeController: Controller { private readonly ApplicationDbContext _context; //db context. private readonly IRepository _repository; public HomeController( ApplicationDbContext context, IRepository repository) { _context = context; _repository = repository; } public IActionResult CreateIndex() { //get the categories. ViewBag.CategoryId = _repository.GetCategories().Select(c => new SelectListItem { Value= c.Id.ToString(),Text = c.CategoryName }).ToList(); return View(); } //get Subcategory based on the category id public IActionResult GetSubCategory(int cid) { var SubCategory_List = _repository.GetCategories().Where(s => s.Id == cid).FirstOrDefault().SubCategories.Select(c => new { Id = c.Id, Name = c.SubCategoryName }).ToList(); return Json(SubCategory_List); } [HttpPost] public IActionResult CreateIndex(ProductViewModel product) { return View(); }
  5. code in the view page (CreateIndex.cshtml), populate only Category dropdown when page loads, then using JQuery to call the action method and populate the subcategory:

     @model MVCDemo.Models.ProductViewModel @{ ViewData["Title"] = "CreateIndex"; } <div class="row"> <div class="col-md-4"> <form asp-action="CreateIndex"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Name" class="control-label"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="CategoryTypeId" class="control-label">Category Type</label> <select asp-for="CategoryTypeId" asp-items="ViewBag.CategoryId" class="form-control"> <option value="">Select Category</option> </select> </div> <div class="form-group"> <label asp-for="SubCategoryTypeId" class="control-label">SubCategory Type</label> <select asp-for="SubCategoryTypeId" class="form-control"></select> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> </div> </div> @section Scripts{ <script> $(function () { $("select#CategoryTypeId").change(function () { var cid = $(this).val(); $("select#SubCategoryTypeId").empty(); $.getJSON(`/Home/GetSubCategory?cid=${cid}`, function (data) { //console.log(data); $.each(data, function (i, item) { $("select#SubCategoryTypeId").append(`<option value="${item.id}">${item.name}</option>`); }); }); }) }); </script> }

The screenshot as below:

在此处输入图像描述

There should be nothing special about this in ASP.Net Core, since the views are still built from basic HTML and CSS and you can use JS.

I'd recommend to follow this tutorial from W3Schools about the topic:https://www.w3schools.com/howto/howto_js_cascading_dropdown.asp

As you can see, in the tutorial the use this nested array as Dropdown data:

var subjectObject = {
  "Front-end": {
    "HTML": ["Links", "Images", "Tables", "Lists"],
    "CSS": ["Borders", "Margins", "Backgrounds", "Float"],
    "JavaScript": ["Variables", "Operators", "Functions", "Conditions"] 
  },
  "Back-end": {
    "PHP": ["Variables", "Strings", "Arrays"],
    "SQL": ["SELECT", "UPDATE", "DELETE"]
  }
}

If your Dropdown data is static you could directly put it in the JS code, but I'd recommend to generate it on the server side and then either:

  1. pass it as view data, serialize it to json and replace the array initialization in the JS code with your literal json string
  2. do a second request from the client to the server (eg using XHR) to some kind of API endpoint and load the Dropdown data as json, then deserialize it and put the data into the dropdown data array. (Don't forget to reload the actual dropdown elements options in this case)

Feel free to ask for clarification if something was not easy to understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM