【问题标题】:Bind DropDownlists with JQuery in Asp.Net在 Asp.Net 中将 DropDownlists 与 JQuery 绑定
【发布时间】:2009-10-18 18:24:21
【问题描述】:

我有 3 个用于 Country、State 和 Metro 的下拉列表。 我想当用户选择 Country 然后 State 下拉列表填充 Jquery 并选择 Sate 然后 Metro 下拉列表填充(如ajax 的级联下拉列表)。这些过程我想用 JQuery 来做。

【问题讨论】:

    标签: asp.net jquery


    【解决方案1】:

    我将在 ASP.NET MVC 中描述它,但如果您编写 ASP.NET Web 服务或只是在代码中添加一些页面方法来执行相同操作,也可以实现相同的效果 - 您将还需要一个 JSON 序列化程序,可以是第 3 方解决方案或 WCF 中的解决方案。

    使用 MVC,首先,让我们有三个控制器动作 - 一个显示页面,国家将是静态的,两个分别获取州和都市:

    public ActionResult Index()
    {
        ViewData["Countries"] = _countryRepository.GetList();
        return View();
    }
    
    public ActionResult States(string countryCode)
    {
        var states = _stateRepository.GetList(countryCode);
        return Json(states);
    }
    
    public ActionResult Metros(string countryCode, string state)
    {
        var metros = _metroRepository.GetList(countryCode, state);
        return Json(metros);
    }
    

    在视图中,你有三个 DropDownLists,一个绑定到 ViewData["Countries"] 对象,假设它被命名为国家,你可以通过这样的 Ajax 调用在 jQuery 中获取状态:

    $('#Countries').change(function() {
        var val = $(this).val();
        $states = $('#States');
        $.ajax({
            url: '<%= Url.Action('States') %>',
            dataType: 'json',
            data: { countryCode: val },
            success: function(states) {
                $.each(states, function(i, state) {
                    $states.append('<option value="' + state.Abbr+ '">' + state.Name + '</option>');
                });
            },
            error: function() {
                alert('Failed to retrieve states.');
            }
        });
    });
    

    Metros 下拉列表将被类推填充,将国家和州选择传递给服务器,并返回一个包含 Metro 区域数组的 JSON 对象。

    我省略了存储库实现的细节,只是在服务器上以某种方式用状态/都市区域的集合填充结果变量。我还假设 State 类将具有两个属性 - Abbr(例如,'CA')和 Name(例如,California)。

    我希望它能以任何方式帮助您,或者至少以某种方式引导您找到解决方案。

    【讨论】:

    • 非常感谢,也为我工作!确实必须在选项值前面放一个 <....>
    • 请注意,如果不解析为json 并返回类似List&lt;T&gt; 的内容,我必须使用states.d,否则属性始终未定义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    相关资源
    最近更新 更多