如何使用ajax绑定下拉列表 [英] how to bind the dropdownlist using ajax

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

问题描述

我需要使用ajax和mvc3

I need to bind the ddl values from another dropdownlist(ddl) result using ajax and mvc3

绑定来自另一个下拉表(ddl)的ddl值相关:如何从ajax json中得到控制器的结果

Related: how to get the result from controller in ajax json

推荐答案

更好地尝试下面的级联下拉列表方法。

Better try the below approach for cascading dropdownlist.

[Script]

function SetdropDownData(sender, args) {           

        $('#ShipCountry').live('change', function () {
            $.ajax({
                type: 'POST',
                url: 'Home/GetCities',
                data: { Country: $('#ShipCountry').val() },
                dataType: 'json',
                success: function (data) {
                    $('#ShipCity option').remove();
                    $.each(data, function (index, val) {                           
                            var optionTag = $('<option></option>');
                            $(optionTag).val(val.Value).text(val.Text);
                            $('#ShipCity').append(optionTag);

                    });
                }
            });
        });

  }

[控制器]

   public IEnumerable<SelectListItem> Cities(string Country)  // ShipCity is filtered based on the ShipCountry value  
    {
        var Cities = new NorthwindDataContext().Orders.Where(c=>c.ShipCountry == Country).Select(s => s.ShipCity).Distinct().ToList();
        List<SelectListItem> type = new List<SelectListItem>();
        foreach (var city in Cities)
        {
            if (city != null)
            {
                SelectListItem item = new SelectListItem() { Text = city.ToString(), Value = city.ToString() };
                type.Add(item);
            }
        }
        return type;
    }
    public ActionResult GetCities(string Country)  
    {
        return Json(Cities(Country), JsonRequestBehavior.AllowGet);

    }

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

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