How can I make a cascading dropdown list?

前端 未结 1 591
旧巷少年郎
旧巷少年郎 2020-12-20 09:04

I have Companies and Vacancies tables.

Company has n number of Vacancies. I need to make two dropdown lists.

In one it will be Company, when I select it, the

相关标签:
1条回答
  • 2020-12-20 09:33

    The idea of cascading dropdown is, When you load the page, you load the dropdown content for the first SELECT element. The second SELECT element will be an empty one. When user selects an option from the first dropdown, send that to the server which returns the content needed to build the second dropdown.

    So in the GET action of your page, get the data needed to render the first dropdown.

    public ActionResult Welcome()
    {
      ViewBag.Companies = new SelectList(db.Companies, "CompanyID", "CompanyName");
      return View();
    }
    

    Now in the view, you can use the DropDownList helper method to render the SELECT element with the data we set to the ViewBag.Companies. We will also add our second dropdown as well.

    @Html.DropDownList("Company", ViewBag.Companies as SelectList)
    <select name="id" id="vacancy" data-url="@Url.Action("Vacancies","Home")">
    

    Now we will use some ajax code(using jQuery in this example) to get the content for the second dropdown. Register an event handler for the change event of the first dropdown, get the selected value, make an ajax call to the Vacancies action method which returns the data needed to build the second dropdown in JSON format. Use this JSON data to build the second dropdown in javascript.

    $(function(){
        $("#Company").change(function (e) {
            var $vacancy = $("#vacancy");
            var url = $vacancy.data("url")+'?companyId='+$(this).val();
            $.getJSON(url, function (items) {
                $.each(items, function (a, b) {
                    $vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
                });
            });
        });    
    });
    

    Now the last part is, implementing the Vacancies method.

    public ActionResult Vacancies(int companyId)
    {
        var items = db.Vacancies
                      .Where(x=>x.CompanyID==comapnyId)
                      .Select(x => new SelectListItem { Value = x.VacancyId.ToString(),
                                                        Text = x.VacancyName })
                      .ToList();
        return Json(items, JsonRequestBehavior.AllowGet);
    }
    

    Assuming db is your DbContext class object.

    Ajax is not necessary for implementing cascading dropdowns. You can post the form with the selected companyId and the action method can return the same with second dropdown filled. But people usually use ajax to give a nice user experience

    0 讨论(0)
提交回复
热议问题