简体   繁体   中英

Jquery and ajax not responding for cascading dropdown

I am having Problem with the AJAX and Jquery Response for the DropDown Cascading. I am trying to Change the State as per the Selection of Country list from the dropdown. I think I am having some problem with my Script.

View :

@using (Html.BeginForm("Submit", "FeedBack", FormMethod.Post)){
@Html.ValidationSummary(true)
@Html.AntiForgeryToken()
<div class="editor-label">
        @Html.LabelFor(model => model.countryid, "Country")
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.countryid, @ViewBag.CountryID as SelectList, "Select Country")
        @Html.ValidationMessageFor(model => model.countryid)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.stateid, "State")
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.stateid, @ViewBag.StateID as SelectList, "Select State")
        @Html.ValidationMessageFor(model => model.stateid)
    </div>
<input type="submit" value="Create" />
}

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
<script type="javascript">
                $(document).ready(function () {
                    $("#countryid").change(function () {
                        // this will call when Country Dropdown select change
                        var countryid = parseInt($("#cointryid").val());
                        if (!isNaN(countryid)) {
                            var ddState = $("#stateid");
                            ddState.empty(); // this line is for clear all items from State dropdown
                            ddState.append($("<option></option").val("").html("Select State"));

                            // Here I will call Controller Action via Jquery to load State for selected Country
                            $.ajax({
                                url: "@Url.Action("GetStates", "Feedback")",
                                type: "GET",
                                data: { countryid: countryid },
                                dataType: "json",
                                success: function (data) {
                                    $.each(data, function (i, item) {
                                        ddState.append(
                                                $("<option></option>").val(item.stateid).html(item.statename)
                                            );
                                    });
                                },
                                error: function () {
                                    alert("Error!");
                                }
                            });
                        }
                    });
                });

Controller:

public class FeedBackController : Controller
{

    CountryStateDB db= new CountryStateDB();


    public ActionResult Submit()
    {
        List<Country> allCountries = new List<Country>();
        List<State> allStates = new List<State>();
        allCountries = db.Countries.OrderBy(a => a.countryname).ToList();
        ViewBag.CountryID = new SelectList(allCountries, "countryid", "countryname");
        ViewBag.StateID = new SelectList(allStates, "stateid", "statename");
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]//// this is for prevent CSRF Attack(cross site Request Attack)
    public ActionResult Submit(FeedBack fb)
    {
        List<Country> allCountry = new List<Country>();
        List<State> allState = new List<State>();

        allCountry = db.Countries.OrderBy(a => a.countryname).ToList();
        if (fb != null && fb.countryid > 0)
        {
            allState = db.States.Where(a => a.countryid.Equals(fb.countryid)).OrderBy(a => a.statename).ToList();
        }
        ViewBag.CountryID = new SelectList(allCountry, "countryid", "countryname", fb.countryid);
        ViewBag.StateID = new SelectList(allState, "stateid", "statename", fb.stateid);

        if (ModelState.IsValid)
        {
            db.FeedBacks.Add(fb);
            db.SaveChanges();
            ModelState.Clear();
            fb = null;
            ViewBag.Message = "Successfully Submitted";
        }
        else
        {
            ViewBag.Message = "Failed! Please try again";
        }
        return View(fb);
    }

    [HttpGet]
    public JsonResult GetStates(string countryid = "")
    {
        List<State> allstate= new List<State>();
        int id = 0;
        if (int.TryParse(countryid, out id))
        {
            allstate = db.States.Where(a => a.countryid.Equals(id)).OrderBy(a => a.statename).ToList();
        }
        if (Request.IsAjaxRequest())
        {
            return new JsonResult
            {
                Data = allstate,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        else
        {
            return new JsonResult
            {
                Data = "Not Valid Request",
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
    }
}

Its countryid not cointryid try this,

$("#countryid").change(function () {
   // this will call when Country Dropdown select change
   var countryid = parseInt(this.value); // use this.value of $(this).val()

You have spelling mistake near "cointryid " please correct it to "CountryId"

And I guess you want to make cascading dropdown list for that try below code..

Script :-

$(document).ready(function () {

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

            $("#StateId").empty();
            $.post("/Home/GetState/", { id: $(this).val() }, function (response) {
             // $("#StatId").append("<option value=''></option>");
              $.each(response, function (index, data) {
                    $("#StateId").append( data.Text);
                });
            });
        });


        $("#StateId").change(function () {

            $("#CityId").empty();
            $.post("/Home/GetCity/", { id: $(this).val() }, function (response) {
                $("#CityId").append("<option value=''></option>");
                $.each(response, function (index, data) {
                    $("#CityId").append("<option value=" + data.Value + ">" + data.Text + "</option>");
                });
            });
        });
    });

Controller :-

 public ActionResult Index()
        {
            var countryList = db.Countries.ToList();

            ViewBag.CountryId = new SelectList(db.Countries, "CountryId", "CountryName");
            ViewBag.StateId = new SelectList(db.States, "StateId", "StateName");
            ViewBag.CityId = new SelectList(db.Cities, "CityId", "CityName");
            return View();
        }

        public JsonResult GetState(int id)
        {
            JsonResult result = new JsonResult();
            var statelist = (from s in db.States
                             where s.CountryId == id
                             select s).ToList();
            var selectlist = new SelectList(statelist, "StateId", "StateName");

            result.Data = selectlist;
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

        public JsonResult GetCity(int id)
        {
            JsonResult result = new JsonResult();
            var dt = db.Cities.Where(y => y.StateId == id);
            List<SelectListItem> mydata = new List<SelectListItem>();
            foreach (var c in dt)
            {
                mydata.Add(new SelectListItem() { Text = c.CityName, Value = c.CityId.ToString() });
            }
            result.Data = mydata;
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

Try this:

@Html.DropDownListFor(model => model.countryid, @ViewBag.CountryID as SelectList, "Select Country", new { @id="countryid" })
@Html.DropDownListFor(model => model.stateid, @ViewBag.StateID as SelectList, "Select State", new { @id="stateid" })

<script type="text/javascript">
    $(function () {
        $("#countryId").change(
        function () {
            loadLevelTwo(this);
        });
        loadLevelTwo($("#countryId"));
    });
    function loadLevelTwo(selectList) {
        var selectedId = $(selectList).val();
        $.ajax(
        {
            url: "@Url.Action("GetStates", "Controller")",
            type: "GET",
            data: { countryid: selectedId },
            success: function (data) {
                $("#stateid").html($(data).html());
            },
        });
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM