Wednesday, May 29, 2013

populating child dropdownlist using JSON Jquery in MVC4 Razor

here i am sharing an example of populating child dropdownlist when changing some value parent dropdownlist

Step 1:
Write two dropdownlist country and state

@Html.DropDownListFor(m => m.CountryId,
            new SelectList(ViewBag.Countries, "Value", "Text"),
            "Select Country", new { data_url = Url.Action("GetStates") })

 @Html.DropDownListFor(m => m.StateId,
            new SelectList(ViewBag.States, "Value", "Text"),
            "Select State")

Step 2:
Write a method in controller which will return JsonResult of states, so that can be consumed using jquery , and populate the state list

public JsonResult GetStates(int countryId)
        {
            IEnumerable< tbState > states = _SecurityService.GetStates(countryId);
         
            return Json(states, JsonRequestBehavior.AllowGet);

         
        }

Step : 3
now lets look at the script, where we get the JSON result and populate the state dropdownlist

< script src="~/Scripts/jquery-1.7.1.min.js" >< /script >

< script >
    $(document).ready(function () {

        $('#CountryId').change(function () {

            var url = $(this).data('url');

            var data = { countryId: $(this).val() };

            $.getJSON(url, data, function (GetStates) {
                var ddlState = $('#StateId');
                ddlState.empty();
                ddlState.append($('< option/ >', {
                    value: 0,
                    text: "Select State"
                }));

                $.each(GetStates, function (index, StateObj) {
                    ddlState.append($('< option/ >', {
                        value: StateObj.StateId,
                        text: StateObj.State
                    }));

                });
            });
        });
    });
< /script >

No comments: