jeudi 13 août 2015

How to call a controller action method from JavaScript to get data in Json formats and populated a drop-down list?

I am trying to make a cascade drop down list i want when user select state then related district or city drop-down list should populated accordingly but in java-script i don't know how to call my action method properly and how it will get cities data from action method? View

                    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
                     <script type="text/jscript">

                        $(function () {
                            $('#State').change(function () {
                                $.getJSON('/Lawyer/GetCities/' + $('#State').val(), function (data) {
                                    var items = '<option>Select a District</option>';
                                    $.each(data, function (i, district) {
                                        items += "<option value='" + district.Value + "'>" + district.Text + "</option>";
                                    });
                                    $('#District').html(items);
                                });
                            });
                        });
                    </script>

                    @Html.DropDownList("state", (SelectList)ViewBag.statevalues, new { id="state"}) 
                    <select id="District" name="District"></select>$

controller :

         'var Statetbl = db.states.ToList();
        List<SelectListItem> stateslist = new List<SelectListItem>();

        var states1 = new List<string>();
        var value = new List<string>();
        foreach (var state_list in Statetbl)
        {
            stateslist.Add(new SelectListItem() { Value = state_list.State_Name, Text = state_list.State_Name });

        }

        ViewBag.statevalues = new SelectList(stateslist, "Text", "Value");`

getcities action method:

 public JsonResult GetCities(string Id)
    {
        var state_id = db.states.Where(m => m.State_Name == Id).First();
        //var related_cities = db.cities.Where(c => c.State_id.Equals(state_id.State_id)).ToList(); 
        List<SelectListItem> citieslist = new List<SelectListItem>();
        var cities = new List<string>();
        var value = new List<string>();
        foreach (var related_city in state_id.cities)
        {
            citieslist.Add(new SelectListItem() { Value = related_city.City_Name, Text = related_city.City_Name });

        }

        return Json(new SelectList(citieslist.ToArray(), "Value", "Text"), JsonRequestBehavior.AllowGet);
    }

Aucun commentaire:

Enregistrer un commentaire