Click here to Skip to main content
14,838,511 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have tried to implement a cascading drop box interface on the view of a form a user can submit.

I have two databases that store the information to populate the drop down lists and another that will store all the information from the form.

In my Controller, I pass the drop down lists to the view via the ViewBag.

Controller:

public ActionResult Add()
    {
        List<country> countries = new List<country>();
        List<city> cities = new List<city>();

        using (EntitiesConnection dc = new EntitiesConnection())
        {
            countries = dc.Countries.ToList();
            cities = dc.Cities.ToList();
        }

        ViewBag.countryId = new SelectList(countries, "id", "name");
        ViewBag.cityId = new SelectList(cities, "id", "name");

        return View();
    }


View:
<div class="editor-label">
            @Html.LabelFor(model => model.name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.name)
            @Html.ValidationMessageFor(model => model.name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.country_id)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.country_id, ViewBag.countryId as SelectList)
            @Html.ValidationMessageFor(model => model.country_id)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.city_id)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.city_id, ViewBag.cityId as SelectList)
            @Html.ValidationMessageFor(model => model.city_id)
        </div>


I also have a POST Action Result to Validate the Form that was submitted as well as a JsonResult.

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Add(Donor donor)
    {
        List<country> countries = new List<country>();
        List<city> cities = new List<city>();

        using (EntitiesConnection dc = new EntitiesConnection())
        {
            var countriesList = dc.Countries.ToList();

            if (donor != null && donor.country_id > 0)
            {
                cities = dc.Cities.Where(a => a.country_id.Equals(donor.country_id)).ToList();
            }
        }

        ViewBag.countryId = new SelectList(countries, "id", "name", donor.country_id);
        ViewBag.cityId = new SelectList(cities, "id", "name", donor.city_id);

        using (EntitiesConnection dc = new EntitiesConnection())
        {
            if (ModelState.IsValid)
            {
                dc.Donors.Add(donor);
                dc.SaveChanges();
            }
        }

        return RedirectToAction("Index", "Donor");
    }

    public JsonResult GetCities(int countryID)
    {
        using (EntitiesConnection dc = new EntitiesConnection())
        {
            var cities = (from a in dc.Cities
                          where a.country_id.Equals(countryID)
                          orderby a.name
                          select a).ToList();

            return new JsonResult { Data = cities, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }


In the View, I have a some javascript code in order for the cascading drop down function to work.

    @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

    <script>
        $(document).ready(function () {
            $("#country_id").change(function () {
                var countryID = parseInt($(this).val());
                if (!isNaN(countryID)) {
                    var $ddcity = $("#city_id");
                    $ddcity.empty();
                    $ddcity.append($("<option></option>").val('').html('wait please ...'));


                    $.ajax({
                        url: '@Url.Action("GetCities", "Donor")',
                        type: 'GET',
                        datatype: 'json',
                        data: { countryID: countryID },
                        success: function (d) {
                            $ddcity.empty();
                            $ddcity.append($("<option></option>").val('').html('select city'));

                            $.each(d, function (i, item) {
                                $ddcity.append($("<option></option>").val(item.id).html(item.name));
                            });
                        },
                        error: function () {
                            alert("error !!");
                        }
                    });
                }
            });
        });
    </script>
}


But for some reason when you select an option from the first dropdown the second dropdown list will not display any of the option that are implemented in the database and the alert message rise an error. Any help would be appreciated.
Please :'(
Posted
Updated 31-Aug-15 23:08pm
v4
Comments
F-ES Sitecore 1-Sep-15 5:35am
   
You can't post hundreds of lines of code, not even all the relevant code, and expect someone to know what the problem is. You need to learn how to debug your code so you can get an idea of what is going on and what the actual issue is. Once you've found the actual issue it might be obvious what the solution is, but if it isn't you can at least ask a more specific question.

http://forums.asp.net/t/1982579.aspx?Using+the+browser+s+dev+tools+to+diagnose+ajax+problems+and+other+things+

http://www.codeproject.com/Articles/79508/Mastering-Debugging-in-Visual-Studio-A-Beginn
hamzah1000 1-Sep-15 6:24am
   
I Think my Question is clear, nice and specific !! :S
F-ES Sitecore 1-Sep-15 6:36am
   
You might think so, but it's not. You posted some actions that aren't relevant to your problem, your code calls a GetCities action that you haven't posted so we can't tell if your js is valid for the action. You haven't said what any error messages are, it could be anything...it could be the data you are sending, or something in the method itself. You can't write loads of code and expect people with no access to your system to tell you what's wrong when it doesn't work. Learning to debug your code is a vital skill that you have to learn. If you follow the first link I posted you should at least be able to get an actual error message from it that will help you along the way. As it stands, no-one can really help you here.

1 solution

It will be good for you.if you will use API and ajax with javascript.You can easly make cascading using above producer.
   
Comments
hamzah1000 2-Sep-15 7:51am
   
How? I didn't have an idea about ur solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900