如何制作级联的下拉列表? [英] How can I make a cascading dropdown list?

查看:125
本文介绍了如何制作级联的下拉列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有公司和空缺"表.

公司有n个职位空缺.我需要列出两个下拉列表.

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

其中之一是公司,当我选择它时,将有与此公司相关的职位空缺.

In one it will be Company, when I select it, there will be Vacancies related to this company.

这是公司的典范

 public Company()
    {
        this.Clients = new HashSet<Client>();
        this.Vacancies = new HashSet<Vacancy>();
    }

    [Key]
    public int CompanyID { get; set; }
    public string CompanyName { get; set; }
    public string Id { get; set; }

    public virtual AspNetUser AspNetUser { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Client> Clients { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Vacancy> Vacancies { get; set; }
}

这里是职位空缺的模型

 public partial class Vacancy
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Vacancy()
    {
        this.Interviews = new HashSet<Interview>();
    }

    [Key]
    public int VacancyId { get; set; }
    public string VacancyName { get; set; }
    public Nullable<int> CompanyID { get; set; }

    public virtual Company Company { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Interview> Interviews { get; set; }

这是我需要执行此操作的控制器

Here is controller where I need to do this

 [HttpGet]
    public ActionResult WelcomeScreen()
    {
        // Формируем список команд для передачи в представление
        SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
        ViewBag.Teams = teams;

        return View();
    }


    //Заносим инфу о вакансии в таблицу
    [HttpPost]
    public ActionResult WelcomeScreen(Interview interview)
    {
        db.Interview.Add(interview);
        db.SaveChanges();
        //Int32 id = interview.Interview_Id;
        //TempData["id"] = id;

        return RedirectToAction("Index", "Questions", new { id = interview.Interview_Id });
    }

我如何制作层叠"下拉列表?

How I need to make Cascade Dropdown list?

更新

我尝试解决方案

这是我的控制器(问题控制器)

Here is my controller (Questions controller)

 [HttpGet]
    public ActionResult WelcomeScreen()
    {
        // Формируем список команд для передачи в представление
        //SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
        //ViewBag.Teams = teams;

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


    //Заносим инфу о вакансии в таблицу
    [HttpPost]
    public ActionResult WelcomeScreen(Interview interview)
    {
        db.Interview.Add(interview);
        db.SaveChanges();
        //Int32 id = interview.Interview_Id;
        //TempData["id"] = id;

        return RedirectToAction("Index", "Questions", new { id = interview.Interview_Id });
    }
    public ActionResult Vacancies(int companyId)
    {
        var items = db.Vacancy
                      .Where(x => x.CompanyID == companyId)
                      .Select(x => new SelectListItem
                      {
                          Value = x.VacancyId.ToString(),
                          Text = x.VacancyName
                      })
                      .ToList();
        return Json(items, JsonRequestBehavior.AllowGet);
    }

这是脚本

 <script>
    $(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>');
                });
            });
        });
    });
</script>

这是[视图]

 <div class="right-grid-in-grid">

                <div style="margin-left:20px;">
                    @Html.DropDownList("Company", ViewBag.Companies as SelectList, new { @class =  "greeting"})
                    @Html.ValidationMessageFor(model => model.VacancyId, "", new { @class = "text-danger" })
                </div>

                <div style="margin-left:20px;">
                    <select name="id" id="vacancy" data-url="@Url.Action("Vacancies","Questions")" class="greeting"/>
                </div>
                </div>

但是AJAX无效.

推荐答案

级联下拉菜单的想法是:加载页面时,将加载第一个SELECT元素的下拉菜单内容.第二个SELECT元素将为空.当用户从第一个下拉菜单中选择一个选项时,将该选项发送到服务器,服务器将返回构建第二个下拉菜单所需的内容.

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.

因此,在页面的GET操作中,获取呈现第一个下拉列表所需的数据.

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();
}

现在在视图中,您可以使用DropDownList帮助器方法使用我们设置为ViewBag.Companies的数据来呈现SELECT元素.我们还将添加第二个下拉列表.

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")">

现在,我们将使用一些ajax代码(在本示例中为使用jQuery )来获取第二个下拉菜单的内容.为第一个下拉列表的change事件注册一个事件处理程序,获取所选值,对Vacancies操作方法进行ajax调用,该方法以JSON格式返回构建第二个下拉列表所需的数据.使用此JSON数据在javascript中构建第二个下拉列表.

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);
}

假设db是您的DbContext类对象.

Assuming db is your DbContext class object.

Ajax对于实现级联下拉列表不是必需的.您可以使用选定的companyId发布表单,并且action方法可以在填充第二个下拉列表的情况下返回该表单.但是人们通常使用ajax来提供良好的用户体验

这篇关于如何制作级联的下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆