如何创建级联下拉列表 [英] How to create cascading drop-down list

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

问题描述

我有两个下拉列表用于过滤目的.如何将该下拉列表更改为追查下拉列表

 public ActionResult Index()
    {
        REFINED_DBEntities db = new REFINED_DBEntities();
        ViewBag.Subdivision =
            new SelectList(db.Retention_Model_Predictions_DS_Manual.Select(m => m.Subdivision).Distinct().OrderBy(c=>c.ToUpper()),

            "Subdivision");

        ViewBag.UnderwriterName =
            new SelectList(db.Retention_Model_Predictions_DS_Manual.Select(m => m.Underwriter_Name).Distinct(),

                "Underwriter_Name");
        return View();
    }

HTML视图

<div class="form-group ">
    @Html.DropDownList("Subdivision", (IEnumerable<SelectListItem>)ViewBag.Subdivision, "Select Region", new { @class = "form-control", @id = "subDivision" })

</div>

<div class="form-group ">
    @Html.DropDownList("Underwriter_Name", (IEnumerable<SelectListItem>)ViewBag.UnderwriterName, "Select Underwriter", new { @class = "form-control", @id = "uwriter" })
</div>

推荐答案

级联下拉菜单的想法是,您在第一个下拉菜单中选择一个值,并触发一些操作以加载第二个下拉菜单的选项-向下.经典示例是国家/地区"下拉列表和州/地区"下拉列表.每次用户选择一个国家/地区时,国家/地区下拉列表都应使用该国家/地区下的州进行更新.

The idea of cascading drop-down is, you select a value in the first drop-down, and it triggers some action to load the options for a second drop-down. A classic example is Country drop-down down and State drop-down. Every time user selects a country the country drop-down should be updated with the states under that country.

我将为您提供一个非常普通的Country-State用例示例.您可以使用相同的概念来构建您的特定用例

首先从开始,为您的视图创建一个视图模型.创建类型为List<SelectListItem>的属性,以传递构建SELECT元素所需的选项列表,以及另一个用于存储所选选项值的属性.我们将对两个SELECT元素都执行此操作.

To start with , create a view model for your view. Create a property of type List<SelectListItem> for passing the list of options needed for building the SELECT element and another property to store the selected option value. We will do this for both the SELECT elements.

public class CreateUserVm
{
   public List<SelectListItem> Countries { set;get;}
   public int SelectedCountryId { set;get;}

   public List<SelectListItem> States { set;get;}
   public int SelectedStateId { set;get;}  

   public CreateUserVm()
   {
     this.Countries = new List<SelectListItem>();
     this.States = new List<SelectListItem>();
   }  
}

现在,在您的GET操作方法中,创建此视图模型的对象,初始化第一个下拉菜单(在本例中为Countries属性)的选项,并将其发送到视图.

Now in your GET action method, create an object of this view model, initialize the options for the first dropdown , in this case the Countries property and send that to the view.

public ActionResult Create()
{ 
    var vm=new CreateUserVm();
    vm.Countries = GetCountries();
    return View(vm);
}
private List<SelectListItem> GetCountries()
{
    var list = new List<SelectListItem>
    {
        new SelectListItem() {Value = "1", Text = "USA"},
        new SelectListItem() {Value = "2", Text = "India"},
    };
    return list;
}

现在在您的视图中,这是我们视图模型的强类型.我们将使用DropDownListFor辅助方法来渲染下拉列表

Now in your View, which is strongly typed to our view model. we will use the DropDownListFor helper method to render the drop-downs

@model CreateUserVm
@using (Html.BeginForm("Index", "Home"))
{
   @Html.DropDownListFor(a=>a.SelectedCountryId,Model.Countries,"Select one")
   @Html.DropDownListFor(a => a.SelectedStateId, Model.States, "Select one",
                                              new { data_url = Url.Action("GetStates") })
   <input type="Submit" />
}

这将呈现2个下拉列表,其中一个具有Country选项,而第二个则为空(因为我们没有将任何内容加载到States属性中).现在我们将有一些javascript(我们在这里使用jquery来进行简单的DOM操作),它将监听第一个dropdown(Country)的change事件,读取所选值并对GetStates进行ajax调用方法并传递所选的国家/地区选项值.

This will render 2 dropdowns, one with Country options and the second one will be empty (because we did not load anything to the States property). Now we will have some javascript(we are using jquery here for easy DOM manipulation) which will listen to the change event of the first drop-down(Country) ,read the selected value and make an ajax call to the GetStates method and passing the selected country option value.

您可以看到,我为第二个下拉菜单设置了html5数据属性,其中将URL存储到GetStates方法.因此,在我的JavaScript中,我可以简单地读取该数据属性值并调用该url以获取数据.

You can see that , i set a html5 data attribute for the second dropdown where i am storing the url to the GetStates method. So in my javascript, i can simply read this data attribute value and make a call to that url to get the data.

$(function () {
    $("#SelectedCountryId").change(function () {
        var v = $(this).val();
        var url = $("#SelectedStateId").data("url") + '?countryId=' + v;
        var $states = $("#SelectedStateId");
        $.getJSON(url, function (states) {
                $states.empty();
                $.each(states, function (i, item) {
                    $states.append($("<option>").text(item.Text).val(item.Value));
                });
            });    
    });
});

现在,让我们添加一个GetStates动作方法,该方法接受countryId并在SelectListItem列表中以JSON数组的形式返回该国家的州.

Now, let's add a GetStates action method which accepts the countryId and return the states for that country in a list of SelectListItem as JSON array.

public ActionResult GetStates(int countryId)
{
    var states = new List<SelectListItem>();
    if (countryId == 1)
    {
        states.Add(new SelectListItem() {Value = "101", Text = "Michigan"});
        states.Add(new SelectListItem() { Value = "102", Text = "New York" });
    }
    else if (countryId == 2)
    {
        states.Add(new SelectListItem() { Value = "103", Text = "Kerala" });
        states.Add(new SelectListItem() { Value = "104", Text = "Goa" });

    }
    return Json(states, JsonRequestBehavior.AllowGet);
}

在这里,我已经对国家和州进行了硬编码.但是,如果您有一个包含此数据的数据库,则用表中的数据替换硬编码值.

Here i have hard coded the Countries and States. But if you have a database which has this data, replace the hard coded values with data from your tables.

编辑记录时,您要做的就是根据保存的CountryId将States属性加载到GET操作中.

When you are editing a record, All you have to do is, load the States property in the GET action based on the CountryId which is saved.

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

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