Click here to Skip to main content
15,883,883 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I want to populate two dropdowns in my MVC project.
First one is for countries and second one for states corresponding to the country selected in the first dropdown. But it is not loading. I couldn't find where the bug is...
In Model
C#
public class CandidateContactUs{
public CandidateContactUs()
        {statesList = new SelectList(new List<SelectListItem>(), "stateID", "state");}
        public SelectList statesList { get; set; }
        private int _countryID;
        [Display(Name = "Country")]
        public int countryID { get { return _countryID; } set { _countryID = value; } }
        public SelectList countries { get { return LoadCountries();}  }
        private int _stateID;
        [Display(Name = "State")]
        public int stateID { get { return _stateID; } set { _stateID = value; } }
        //private IList<SelectListItem> _states;
        public IList<SelectListItem> states { get; set; }
private SelectList LoadCountries()
        {TestMVC.Models.SMTestEntities objSMWebDefaultConnection = new TestMVC.Models.SMTestEntities();
            var countryList = objSMWebDefaultConnection.tblCountries.Where(c => c.recordActive == true).Select(c => new { c.countryID, c.country }).ToList();
            return new SelectList(countryList, "countryID", "country");}

In Controller
SQL
public ActionResult ContactUs()
{ CandidateContactUs contactUs = new CandidateContactUs();
    return View(contactUs);}
 TestMVC.Models.SMTestEntities objSMWebDefaultConnection = new TestMVC.Models.SMTestEntities();
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult LoadStatesList(int countryID)
        {            var statesList = objSMWebDefaultConnection.tblStates.Where(s => s.recordActive == true && s.countryID == countryID).Select(s => new { s.stateID, s.state }).ToList();
            return Json(statesList, JsonRequestBehavior.AllowGet);

In View

@Html.DropDownListFor(model => model.countryID, Model.countries, new { @id = "drpCountry" })
@Html.ValidationMessageFor(model => model.countryID)


<label for="stateID">
State</label>


@Html.DropDownListFor(model => model.stateID, Model.statesList, new { @id = "drpState" })

XML
<script type="text/javascript">
            $(function () {
                $("#drpCountry").change(function () {
                    var countryID = $("#drpCountry").val();
                    $.ajax({
                        cache: false,
                        type: "GET",
                        url: '@(Url.RouteUrl("LoadStatesList"))',
                        data: { "countryID": countryID },
                        success: function (stateArray) {
                            if (stateArray.d != null) {
                                if (stateArray.d.length != 0) {
                                    $.each(stateArray, function (id, option) {("#drpState").append($('<option></option>').val(option.stateID).html(option.state));  });
                                }
                            }
                        },
                        error: function () {
                            alert("Failed to load states. Please try again.");
                        }
                    });
                });
            });
        </script>


Any one Please help me..
Posted
Updated 3-Nov-14 2:37am
v2
Comments
Jineesh TR 3-Nov-14 23:10pm    
Thank You All.. Now the function from controller executes properly but not able to read this list in the javascript function.
When I see the log file the received file is an object array. How can I read this. Can you help me.

Hello Jini4.. This code will work. Check it..
Change the controller name.. :)(In my system this code working fine )

JavaScript
<script type="text/javascript">
            $(function () {
                $("#drpCountry").change(function () {
                    var countryID = $("#drpCountry").val();
                    $.ajax({
                        cache: false,
                        type: "GET",
                        url: "/Home/LoadStatesList",
                        data: { "countryID": countryID },
                        success: function (stateArray) {
                            if (stateArray != null) {
                                if (stateArray.length != 0) {
                                    $.each(stateArray, function (id, option) {
                                        var newOption = "<option value='" + id + "'>" + option.state + "t</option>";
                                        $("#drpState").append(newOption);
                                    });
                                }
                            }
                        },
                        error: function () {
                            alert("Failed to load states. Please try again.");
                        }
                    });
                });
            });
</script>
 
Share this answer
 
v3
Comments
Jineesh TR 3-Nov-14 22:54pm    
Thank You Shemeemsha.. The function from controller executes properly but not able to read this list in the javascript function.
When I see the log file the received file is an object array. Can you help me.
Did you referenced the url in your RouteConfig?

Try to add this code:

routes.MapRoute("LoadStatesList",
                           "Controller/LoadStatesList/",
                           new { controller = "ControllerName", action = "LoadStatesList" },
                           new[] { "yourSolutionName.Controllers" });


And i will highly recommend this link to you:

Cascading Dropdown List With MVC, LINQ to SQL and AJAX
 
Share this answer
 
Comments
Jineesh TR 3-Nov-14 22:51pm    
Thanks PetarS089. I have included it. But even then it is not working. The problem comes after returning data from the actionResult LoadStatesList. The function executes properly but not able to read this list there in the javascript function. Can you help me.
Quote:
Hi every one...
At last I have got the result properly.
Thank you all for your support.
The answer is shown below.
JavaScript
<script type="text/javascript">
            $(function () {
                $("#drpCountry").change(function () {
                    var countryID = $("#drpCountry").val();
                    $.ajax({
                        cache: false,
                        type: "GET",
                        url: '@(Url.RouteUrl("LoadStatesList"))',
                        data: { "countryID": countryID },
                        success: function (stateArray) {

                            $("#drpState").html('');
                            if (stateArray.length > 0) {
                             
                                
                                for (i = 0; i < stateArray.length; i++) {

                                    $("#drpState").append($('<option></option>').val(stateArray[i].stateID).html(stateArray[i].state));
                                }
                                callback.call(this);
                            }
                        },
                        error: function () {
                            alert("Failed to load states. Please try again.");
                        }
                    });
                });
            });
        </script>


regards,
jini4
 
Share this answer
 
 
Share this answer
 
Comments
Shemeemsha (ഷെമീംഷ) 3-Nov-14 9:40am    
Please read the question first and answer it..

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