skip to Main Content

I am writing a logic to display list of States on selection on Country.

I am using jQuery Ajax for this so that the State list gets updated instantly without reload of page.

I am stuck at place where I am getting the State list for selected Country but not aware to pass the jSon return type in view using ajax. Below is my code

View

<table>
<tbody>
<td>
    
@Html.DropDownList("countryVal", (IEnumerable<SelectListItem>)ViewBag.countryVal, "Select Country", new { @id = "Country" })
    
</td>

<td>
<select id="state">Selet State

</select>
</td>
</tbody>
</table>
<script src="~/Scripts/jquery-3.6.3.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
    $("select").change(function () {
        var selectedCountry = $(this).children("option:selected").text();

        alert(selectedCountry);

        if (selectedCountry != '') {

            alert("Working")

            $('#state').empty();
            $.ajax({
                type: 'POST',
                url: "/Home/GetStates",
                data: { selectedCountry: selectedCountry },
                success: function (data) {
                    if (data && data.length > 0) {
                        $.each(res, function (i, item) {
                            $('#state').append(new Option(item.stateName, item.stateId));
                        });
                    }
                }
            })
        }

        
    });
});  
</script>

Controller

public ActionResult DropDown()
{

    using (Db db = new Db())
    {
        ViewBag.countryVal = new SelectList(db.Countries.ToList(), "countryId", "CountryName");

        //ViewBag.stateName = new SelectList(db.States.ToList(),"stateId","stateName");

        //var test = ViewBag.countryVal;

        return View();
    }
}

[HttpPost]
public JsonResult GetStates(string selectedCountry)
{
    using (Db db = new Db())
    {
        Country data = db.Countries.Where(x => x.CountryName == selectedCountry).FirstOrDefault();

        int id = data.countryId;
        List<State> stateList = db.States.Where(x => x.countryId == id).ToList();

        ViewBag.ID = id;

        ViewBag.SList = stateList;

        return Json(stateList, JsonRequestBehavior.AllowGet);
    }

        
}

Any help is much appreciated.

Thank you

2

Answers


  1. Chosen as BEST ANSWER

    Here is the solution and working code for State but Country list not working

    $(document).ready(function () {
        var noCountry = $("#Country").children("option:selected").text();
    
        if (noCountry != '') {
    
            $('#state').append("<option value='0'>Selet State</option>");
        }
    
        $("#Country").change(function () {
    
    
            debugger;
    
            var selkt = noCountry;
    
            var selectedCountry = $(this).children("option:selected").text();
    
    
            //alert(selectedCountry);
            $('#state').empty();
    
            $('#state').append("<option value='0'>Selet State</option>");
    
    
            if (selectedCountry != '') {
    
                //alert("Working")
    
    
                $.ajax({
                    type: 'POST',
                    url: "/Home/GetStates",
                    data: { selectedCountry: selectedCountry },
                    success: function (data) {
    
                        if (data && data.length > 0) {
                            $.each(data, function (i, item) {
                                $('#state').append(new Option(item.stateName, item.stateId));
                            });
                        }
                    }
                })
            }
    
    
        });
    
    
        $('#cityList').append("<option value='0'>Select City</option>").text();
    
        $('#state').change(function () {
    
    
            var stateSelected = $('#state').children("option:selected").text();
    
            if (stateSelected != 'Selet State' | stateSelected != '') {
                //debugger;
    
                $.ajax({
                    type: 'POST',
                    url: "/Demo/GetCity",
                    data: { stateSelected: stateSelected },
                    success: function (data) {
                        debugger;
                        if (data && data.length > 0) {
                            $.each(data, function (i, items) {
    
                                $('#cityList').append(new Option(items.cityName, items.cityId));
    
                            });
                        }
                    }
    
                });
            }
        });
    });
    

    So, helped adding a debugger and identify the breaking point.


  2. You don’t need to put the list in the viewbag in Jayson

    <select id="state">
    </select>
    

    Suppose state has Name and Id fields

    $('#state').empty();
    $.ajax({
           type: 'POST',
           url: "/Home/GetStates",
           data: { selectedCountry: selectedCountry },
           success: function (data) {
               if(data && data.length>0){
                 $.each(res,function(i,item){
                   $('#state').append(new Option(item.Name, item.Id));
                 });
               }
             }
      })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search