Click here to Skip to main content
14,980,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello All,

I am having trouble to get values according to CountryID, StateID into the City drop down list, here is my HomeController.cs class code :
C#
public class HomeController : Controller
    {
        MVCDDEntities _entities = new MVCDDEntities();
        public ActionResult Index()
        {
            ViewBag.Countries = _entities.Countries.ToList();
            ViewBag.States = _entities.States.ToList();
            ViewBag.Cities = _entities.Cities.ToList();
            return View();
        }

        //Get all the states based on CountryID
        public IList<state> GetStates(int countryID)
        {
            return _entities.States.Where(c => c.CountryID == countryID).ToList();
        }

        //Get all the cities based on StateID
        public IList<city> GetCitis(int stateID)
        {
            return _entities.Cities.Where(c => c.StateID == stateID).ToList();
        }
        

        //filter state based on countryID
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadStatesByCountryID(string countryID)
        {
            var stateList = this.GetStates(Convert.ToInt32(countryID));
            var stateData = stateList.Select(c => new SelectListItem() { 
                Text = c.StateName,
                Value = c.StateID.ToString(),
            });
            return Json(stateData,JsonRequestBehavior.AllowGet);
        }

        //filter city based on stateID
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadCitiesByStateID(string stateID)
        {
            var cityList = this.GetCitis(Convert.ToInt32(stateID));
            var cityData = cityList.Select(c => new SelectListItem()
            {
                Text = c.CityName,
                Value = c.CityID.ToString(),
            });
            return Json(cityData, JsonRequestBehavior.AllowGet);
        }
}

And here is my view code :
C#
@model MVCCascading.MVCDDEntities
@{
    ViewBag.Title = "Index";
}

<p>
    @Html.DropDownListFor(Model => Model.Countries, new SelectList(ViewBag.Countries as System.Collections.IEnumerable, "CountryID", "CountryName"),

            "Select a Country", new { id = "ddlCountry" })
</p>
<p>
    @Html.DropDownListFor(Model => Model.States, new SelectList(Enumerable.Empty<SelectListItem>(), "StateID", "StateName"),
            "Select a State", new { id = "ddlStates" })
</p>
<p>
    @Html.DropDownListFor(Model => Model.Cities, new SelectList(Enumerable.Empty<SelectListItem>(), "CityID", "CityID"),
            "Select a City", new { id = "ddlCities" })
</p>

@section scripts
{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#ddlCountry").change(function () {
                var countryID = $(this).val();
                $.getJSON("../Home/LoadStatesByCountryID", { countryid: countryID },
                    function (stateData) {
                        var select = $("#ddlStates");
                        //alert(select);
                        select.empty();
                        select.append('<option/>', {
                            value: 0,
                            text: "Select a State"
                        });

                        $.each(stateData, function (index, itemData) {
                            //alert(index);
                            alert(stateData);
                            alert(itemData);
                            select.append('<option/>', {
                                value: item.Value,
                                text: itemData.Text
                            });
                        });
                    });
            });
        });
    </script>
}

I am getting 0 values in state list?
Can anyone help me to get out of this?

Thanks
Posted
Updated 11-Oct-14 2:12am
v4
Comments
   
Put a debugger and see if you are getting anything on statesData?
DT_2 11-Oct-14 2:24am
   
Yes getting the values in stateData.
   
See my answer...

1 solution

I can see one problem here.
JavaScript
$.each(statesData, function (index, itemData) {
    //alert(index);
    alert(statesData);
    alert(itemData);
    select.append('<option/>', {
        value: item.Value,
        text: itemData.Text
    });
});

Here what is item? It should be itemData I guess. If you get any further issues, then see the console tab of developer tool.
Comments
DT_2 11-Oct-14 3:22am
   
yes it is itemData. and its not statesData, it is stateData. But didn`t get solution,state list is empty.
   
Where have you assigned the returned data to state data? I cannot see in code. Have you checked the console tab of developer tool?
DT_2 11-Oct-14 6:29am
   
No sir, I don`t know how to use console tab? Sorry:-(
   
Okay, tell me where you have assigned values to statesData?
DT_2 11-Oct-14 6:41am
   
In Home Controller, in LoadStatesByCountryID Action method, from where I am returning the Json object.
   
Are you sure this method is returning states correctly? Have you debugged? Just put a debugger in code by writing debugger;.
DT_2 11-Oct-14 6:58am
   
I am not getting the stateData values on View, but getting on controller when I am debugging the code.
   
In controller the name is stateData, but in jQuery it is statesData. This might be the issue.
DT_2 11-Oct-14 8:05am
   
Sir, i mentioned it in earlier reply. But it is not the issue.
   
Then please check developer console. You will get the issue. If you use Firefox, then install firebug and see the console tab.
DT_2 11-Oct-14 8:14am
   
ok:-(
   
Don't be sad. You should have the skill of debugging inside developer tools. So, let's do this.
   
If you are getting data, then try like below... Modify the code according to your variables.

var dest = $(selobj);
console.log('populating data to options', data, dest.length);
$.each( data, function(key,value) {
console.log(' option', key, value);
var el = $('<option></option>')
.attr('value', key)
.html( value);
dest.append( el);
});
DT_2 11-Oct-14 8:06am
   
Nope:-(

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