如何将数据添加到下拉列表中?

时间:2011-09-07 10:51:52

标签: asp.net asp.net-mvc

嗨朋友们,我想在第二页的两个字段中开发一个注册页面 1.state 2.district(都是下拉列表)。 现在我的问题是如何动态获取数据,如果选择状态字段,它将显示所有可用的状态。 例如,有三种状态1.A 2.B 3.C. 每个州包含4个区

state      district1   district1     district1   district1
A           AAA1        AAA2          AAA3         AAA4      
B           BBB1        BBB2          BBB3         BBB4
c           CCC1        CCC2          CCC3         CCC4

如果我选择状态A,则必须仅显示州区

请告诉我如何在asp.net中做到这一点

1 个答案:

答案 0 :(得分:2)

与往常一样,您首先要定义视图模型:

public class MyViewModel
{
    [Required]
    [DisplayName("Select a state:")]
    public string SelectedState { get; set; }
    public IEnumerable<SelectListItem> States { get; set; }

    [Required]
    [DisplayName("Select a district:")]
    public string SelectedDistrict { get; set; }
    public IEnumerable<SelectListItem> Districts { get; set; }
}

然后是控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            // TODO: load the states initially
            States = new[] { "A", "B", "C" }.Select(x => new SelectListItem
            {
                Value = x,
                Text = x
            }),
            // Initially we don't have districts
            Districts = Enumerable.Empty<SelectListItem>()
        };
        return View(model);
    }

    public ActionResult Districts(string state)
    {
        // TODO: given a state select its districts
        var districts = Enumerable
            .Range(1, 4)
            .Select(x => string.Format("district {0} of state {1}", x, state));
        return Json(districts, JsonRequestBehavior.AllowGet);
    }
}

然后是一个观点:

@model MyViewModel

<div>
    @Html.LabelFor(x => x.SelectedState)
    @Html.DropDownListFor(
        x => x.SelectedState, 
        Model.States, 
        "-- State --", 
        new { 
            id = "states", 
            data_url = Url.Action("districts") 
        }
    )
</div>

<div>
    @Html.LabelFor(x => x.SelectedDistrict)
    @Html.DropDownListFor(
        x => x.SelectedDistrict, 
        Model.Districts, 
        "-- District --", 
        new { id = "districts" }
    )
</div>

最后是一些javascript来级联States下拉列表:

$(function () {
    $('#states').change(function () {
        var url = $(this).data('url');
        var selectedState = $(this).val();
        $.get(url, { state: selectedState }, function (districts) {
            var districtsDdl = $('#districts');
            districtsDdl.empty();
            $.each(districts, function (index, district) {
                districtsDdl.append(
                    $('<option/>', {
                        value: district,
                        text: district
                    })
                );
            });
        });
    });
});