Ad

Search This Blog

Friday, July 24, 2015

Cascading Dropdowns in MVC4

Binding Initial Dropdown Code :

 region = workTrayRepository.GetRegions();
                var regionSelectList = new SelectList(region, "RegionId", "Region");
                ViewBag.Regions = regionSelectList;


In the View :-

  @Html.DropDownList("ddlRegion", ViewBag.Regions as SelectList, "----- Select Region -----")


In Selection Change event of  First DropDown , we need to populate Second Drop down. We can do this using JQuery with Ajax.

In the View Drop Down:-

@Html.DropDownList("ddlofficer", new SelectList(string.Empty, "Value", "Text"), "Please select a HO Name", new { style = "width:250px", @class = "dropdown1" })


 $(document).ready(function (e) {
        $('#ddlRegion').change(function (e) {
            e.preventDefault();
            var regionName = $(this).find(":selected").text();
           
            $("#ddlofficer").empty();

            $.ajax({
                type: 'GET',
                url: '@Url.Action("BindOfficersDetails")', 
                dataType: 'json',
                data: { regionName: $(this).find(":selected").text() },
                success: function (data) {

                    $.each(data, function (id, state) {
                        $("#ddlofficer").append('<option value="' + state.Value + '">' + state.Text + '</option>');
                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });

            });
        });


In the C# Code :-

 public ActionResult BindOfficersDetails(string regionName)
        {
            var officers = new List<DTO_Officers>();
            officers = workTrayRepository.GetOfficersBySelectRegionWise(regionName.ToString().Trim());
            return Json(new SelectList(officers.ToArray(), "RId", "HOName"), JsonRequestBehavior.AllowGet);
        }




No comments:

Post a Comment