Kazim Hussain
Kazim Hussain

Reputation: 27

Cascading dropdown list using jquery ajax in asp.net mvc

I am just a beginner with MVC and JQuery. I am trying to create a simple cascading dropdownlist application with Country,State and City as a three dropdowns. I have used a JQuery ajax as a scripting to handle Dropdown change event.

enter code here

Countries load from database normally and states load correctly in dropdown but cities even don't load i have debugged a lot but could not find solution.

Can anyone help me in this.

Below are the functions defined in the controller part

public JsonResult GetCityByStateId(int stateId)
        {
            using (MyDbContext db = new MyDbContext())
            {
                List<tblCity> lstCities = new List<tblCity>();
                lstCities = db.tblCities.Where(x => x.StateId == stateId).ToList();


                var lstToReturn = lstCities.Select(s => new { id = s.Id, Name = s.Name });
                return Json(lstToReturn, JsonRequestBehavior.AllowGet);

            }
        }


   public JsonResult GetStatesByCountryId(int countryId)
        {
            using (MyDbContext db = new MyDbContext())
            {
                List<tblState> lstStates = new List<tblState>();
                lstStates = db.tblStates.Where(x => x.CountryId == countryId).ToList();

                var lstToReturn = lstStates.Select(s => new { id = s.Id, Name = s.Name });
                return Json(lstToReturn, JsonRequestBehavior.AllowGet);


            }
        }

Here is My View

<div class="row">
                        <div class="col-sm-12 col-md-6">

                            <div class="form-group" style="margin-left:10px;">
                                <label>Country</label>
                                <select id="CountryId" name="CountryId" required class="form-control show-tick">
                                    <option value="-1">Select Country</option>
                                    @if (lstCountry.Count > 0 && lstCountry != null)
                                    {
                                        foreach (var item in lstCountry)
                                        {
                                            <option value="@item.Id">@item.Name</option>
                                        }
                                    }
                                </select>

                            </div>

                        </div>

                        <div class="col-sm-12 col-md-6">

                            <div class="form-group" style="margin-right:10px;">
                                <label>Province</label>
                                <select id="SateId" required name="SateId" class="form-control"></select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-12 col-md-6">

                            <div class="form-group" style="margin-left:10px;">
                                <label>City</label>
                                <select id="CityId" name="CityId" class="form-control" required></select>
                            </div>
                        </div>
                    </div>

And below that is my script

 $(document).ready(function () {

    var ddlcountries = $('#CountryId');
    var ddlstates = $('#SateId');
    var ddlCities = $('#CityId');

    var txtConfirmPassword = $('#ConfirmPassword');
    var txtPassword = $('#Password');

    txtConfirmPassword.change(function () {
        if (!(txtPassword.val() == txtConfirmPassword.val())) {
            $('#lblPassword').text('Password & Confirm password does not match');
            $('#lblPassword').css('color', 'red');
        }
    })

    ddlcountries.change(function () {
        if ($(this).val() == '-1') {
            ddlstates.empty();
            ddlCities.empty();
            ddlstates.append($('<option/>', { value: -1, text: 'Select States' }));
            ddlCities.append($('<option/>', { value: -1, text: 'Select City' }));
            ddlcountries.val('-1');
            ddlstates.val('-1');
            ddlCities.val('-1');
            ddlstates.prop('disabled', true);
            ddlCities.prop('disabled', true);

        }
        else {
            alert(ddlcountries.val());
            $.ajax({
                url: '/Employer/GetStatesByCountryId',
                method: 'post',
                data: { countryId: $(this).val() },
                dataType: 'json',
                success: function (data) {
                    ddlstates.empty();
                    ddlstates.append($('<option/>', { value: -1, text: 'Select States' }))
                    ddlstates.prop('disabled', false);
                    $(data).each(function (index, item) {
                        ddlstates.append($('<option/>', { value: item.Id, text: item.Name }))
                    })
                }
            });

        }
    })

    ddlstates.change(function () {
        if ($(this).val() == '-1') {
            alert(ddlstates.val());
            ddlCities.empty();
            ddlCities.append($('<option/>', { value: -1, text: 'Select City' }));
            ddlCities.val('-1');
            ddlCities.prop('disabled', true);

        }
        else {
            alert(ddlstates.val());
            $.ajax({
                url: '/Employer/GetCityByStateId',
                method: 'post',
                data: { stateId: $(this).val() },
                dataType: 'json',
                success: function (data) {
                    ddlCities.empty();
                    ddlCities.append($('<option/>', { value: -1, text: 'Select City' }))
                    $(data).each(function (index, item) {
                        ddlCities.append($('<option/>', { value: item.Id, text: item.Name }))
                    })
                    ddlCities.prop('disabled', false);
                    ddlCities.val('-1');
                },
                error: function (err) {
                    alert(err + ' ' + $(this).val());
                }
            });

        }
    })



})

When i change my country dropdown and alerts its value it is giving me correct value but in same case if do this for states dropdown i get text(states names) of dropdown so that's where i am mistaken but please solve my problem thanks in advance..........

Upvotes: 0

Views: 2481

Answers (1)

Matt Bodily
Matt Bodily

Reputation: 6423

from your comment about it not firing I am guessing your issue is with the url. from here https://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.action(v=vs.118).aspx I would suggest you change

url: '/Employer/GetStatesByCountryId',

to

url: '@Url.Action("GetStatesByCountryId", "Employer")',

which will build a url with your server location added to the front

Upvotes: 1

Related Questions