on select change事件 - Html.DropDownListFor

时间:2011-04-25 21:12:31

标签: c# asp.net-mvc-3 razor

我有两个下拉列表。第一个选定的值加载另一个。当我在控制器中有辅助方法时,我该怎么做?

@using (Html.BeginForm())
{
<div>
    <table width="100%" cellpadding="0" cellspacing="0">
        <tr>
            <td><b>Select a District:</b></td>
            <td>@Html.DropDownListFor(m => m.DistrictId, ViewData["DMManagers"] as IEnumerable<SelectListItem>, "Select One")</td>
        </tr>
        <tr>
            <td><b>Select a TM:</b></td>
            <td>@Html.DropDownListFor(m => m.TMId, ViewData["TMManagers"] as IEnumerable<SelectListItem>, "Select One")</td>
        </tr>
    </table>
</div>
}

private void LoadDistrictManagers()
{
    var _DMS = (from c in SessionHandler.CurrentContext.ChannelGroups
                join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
                where cgt.Name == "District Manager"
                select new { c.ChannelGroupId, c.Name }).OrderBy(m => m.Name);
    ViewData["DMManagers"] = new SelectList(_DMS, "ChannelGroupId", "Name");
}

private void LoadTerritoryManagers(int districtId)
{
    var _TMS = (from c in SessionHandler.CurrentContext.ChannelGroups
                join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
                where cgt.Name == "Territory" && c.ParentChannelGroupId == districtId
                select new { c.ChannelGroupId, c.Name }).OrderBy(m => m.Name);
    ViewData["TMManagers"] = new SelectList(_TMS, "ChannelGroupId", "Name");
}

public ActionResult SummaryReport()
{
    DistrictManagerModel model = new DistrictManagerModel();
    LoadDistrictManagers();
    return View("AreaManager", model);
}

3 个答案:

答案 0 :(得分:31)

使用HTTPAttributes字段为两个下拉列表提供唯一ID:

@Html.DropDownListFor(m => m.DistrictId, ViewData["DMManagers"] as IEnumerable<SelectListItem>, "Select One", new {@id="ddlDMManagers"})

第二个下拉列表应初始化为空列表:

@Html.DropDownListFor(m => m.TMId, Enumerable.Empty<SelectListItem>(), new {@id="ddlTMManagers"})

如果您不介意在第一个下拉列表中触发'更改'事件时使用jQuery ajax更新第二个下拉列表:

$(function() {
    $('select#ddlDMManagers').change(function() {
        var districtId = $(this).val();


        $.ajax({
            url: 'LoadTerritoryManagers',
            type: 'POST',
            data: JSON.stringify({ districtId: districtId }),
            dataType: 'json',
            contentType: 'application/json',
            success: function (data) {
                $.each(data, function (key, TMManagers) {
                    $('select#ddlTMManagers').append('<option value="0">Select One</option>');
                    // loop through the TM Managers and fill the dropdown
                    $.each(TMManagers, function(index, manager) {
                        $('select#ddlTMManagers').append(
                            '<option value="' + manager.Id + '">'
                            + manager.Name + 
                            '</option>');
                    });
                });
            }
        });
    });
});

将此类添加到控制器命名空间:

public class TMManager
{
    public int Id {get; set;}
    public string Name {get; set;}
}

您需要更新控制器操作LoadTerritoryManagers(),以响应ajax请求并返回{Id,Name}对象的JSON数组。

    [HttpPost]
    public ActionResult LoadTerritoryManagers(int districtId)
    {
        var _TMS = (from c in SessionHandler.CurrentContext.ChannelGroups
                join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
                where cgt.Name == "Territory" && c.ParentChannelGroupId == districtId
                select new TMManager(){ Id = c.ChannelGroupId, Name = c.Name }).OrderBy(m => m.Name);

        if (_TMS == null)
            return Json(null);

        List<TMManager> managers = (List<TMManager>)_TMS.ToList();
        return Json(managers);
    }

答案 1 :(得分:1)

使用以下代码。它用在我的项目中。对于区域和区域,我使用了两个下拉列表。在更改区域数据时,我加载了区域下拉列表。

在查看页面

 @Html.DropDownList("ddlZone", new SelectList(@ViewBag.Zone, "Zone_Code", "Zone_Name"), "--Select--", new { @class = "LoginDropDown" })

 @Html.DropDownList("ddlRegion", Enumerable.Empty<SelectListItem>(), new { @class = "LoginDropDown" })

加载视图页面时需要加载区域。

在控制器中为区域加载

编写此方法
 [WebMethod]
        public JsonResult LoadRegion(string zoneCode)
        {
            ArrayList arl = new ArrayList();

            RASolarERPData objDal = new RASolarERPData();
            List<tbl_Region> region = new List<tbl_Region>();

            region = erpDal.RegionByZoneCode(zoneCode);

            foreach (tbl_Region rg in region)
            {
                arl.Add(new { Value = rg.Reg_Code.ToString(), Display = rg.Reg_Name });
            }

            return new JsonResult { Data = arl };
        }

然后使用以下JavaScript

<script type="text/javascript">

        $(document).ready(function () {

        $('#ddlZone').change(function () {
            LoadRegion(this.value);
        });

        function LoadRegion(zoneCode) {

            $.ajax({
                type: "POST",
                url: '@Url.Action("LoadRegion", "RSFSecurity")',
                data: "{'zoneCode':'" + zoneCode + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                cache: false,
                success: function (data) {
                    $('#ddlRegion').get(0).options.length = 0;
                    $('#ddlRegion').get(0).options[0] = new Option("--Select--", "0");

                    $.map(data, function (item) {
                        $('#ddlRegion').get(0).options[$('#ddlRegion').get(0).options.length] = new Option(item.Display, item.Value);
                    });
                },
                error: function () {
                    alert("Failed to load Item");
                }
            });
        }

    });

</script>

答案 2 :(得分:1)

我们可以使用jquery来获取和填充下拉列表:

<script>
  function FillCity() {
    var stateId = $('#State').val();
    $.ajax({
        url: '/Employees/FillCity',
        type: "GET",
        dataType: "JSON",
        data: { State: stateId},
        success: function (cities) {                    
            $("#City").html(""); // clear before appending new list 
            $.each(cities, function (i, city) {
                $("#City").append(
                    $('<option></option>').val(city.CityId).html(city.CityName));
            });
        }
    });
  }
</script>

有关详细信息,请参阅 MVC DropDownListFor fill on selection change of another dropdown