如何用ajax绑定DropDownList的 [英] how to bind the dropdownlist using ajax

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

问题描述

我需要使用Ajax和MVC3从其他的DropDownList(DDL)的结果绑定DDL值

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

相关阅读:<一href="http://stackoverflow.com/questions/14744753/how-to-get-the-result-from-controller-in-ajax-json/14745087#comment20636572_14745087">how从控制器得到的结果在AJAX JSON

推荐答案

最好尝试以下方法级联DropDownList的。

Better try the below approach for cascading dropdownlist.

[脚本]

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

                    });
                }
            });
        });

  }

[控制器]

[Controller]

   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绑定DropDownList的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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