on select change event - Html.DropDownListFor

后端 未结 3 417
野的像风
野的像风 2020-12-01 05:49

I have two dropdownlist. The selected value from the first one loads the other. How do I do that when I have the helper methods in a controller?

@using (Html         


        
相关标签:
3条回答
  • 2020-12-01 05:58

    We can use the jquery to get and fill the dropdown like this:

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

    For more detail see MVC DropDownListFor fill on selection change of another dropdown

    0 讨论(0)
  • 2020-12-01 06:13

    Use the following code. It is used in my project. For Zone and Region I used two drop-down list. On change Zone data I loaded the Region drop-down.

    In View page

     @Html.DropDownList("ddlZone", new SelectList(@ViewBag.Zone, "Zone_Code", "Zone_Name"), "--Select--", new { @class = "LoginDropDown" })
    
     @Html.DropDownList("ddlRegion", Enumerable.Empty<SelectListItem>(), new { @class = "LoginDropDown" })
    

    The Zone need to load when the view page is load.

    In the controller write this method for Region Load

     [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 };
            }
    

    Then use the following 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>
    
    0 讨论(0)
  • 2020-12-01 06:22

    Give both dropdowns unique IDs using the HTTPAttributes field:

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

    2nd dropdown should be initialized as an empty list:

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

    If you don't mind using jQuery ajax to update the 2nd dropdown when a 'change' event is triggered on the 1st dropdown:

    $(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>');
                        });
                    });
                }
            });
        });
    });
    

    Add this class to your controller namespace:

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

    You will need to update your controller action, LoadTerritoryManagers(), to respond to the ajax request and return a JSON array of {Id,Name} objects.

        [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);
        }
    
    0 讨论(0)
提交回复
热议问题