Smoking monkey
Smoking monkey

Reputation: 323

Cascading dropdown lists in Mvc 4.0

I have been trying to cascade dropdown lists. For this purpose I am using javascript in .cshtml page . Don't know what is the reason , I'm not able to even call Js method , leave alone the controller method which later needs to be called from within the Js method. Dropdowns are fetching the state and city data but I'm not getting the city according to the state selected.

<div class="editor-label">
    @Html.LabelFor(model => model.State_Id)
</div>
<div class="editor-field">
    @Html.DropDownList("State",null,"Select State", new {@class="span4", id="State"})
    @Html.ValidationMessageFor(model => model.State_Id)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.CityId)
</div>
<div class="editor-field">
    @Html.DropDownList("City",null,"Select City", new {@class="span4", id="City"})
    @Html.ValidationMessageFor(model => model.CityId)
</div>

<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" >
    $(document).ready(function(e) {
        $("#State").change(function (e) {
            var selectedValue = $(this).val();
            if(selectedValue != "Select") {
                $.ajax({
                    url: '@Url.Action("GetCities","Employer")',
                    type: 'Post',
                    //data:  { "selectedValue": selectedValue},
                    data: {id: $("#State").val()},
                    dataType: 'json',
                    success: function(response) {
                        var items = "";
                        $.each(response, function(i, city) {
                            $("#City").append('<option value="' + city.Value + '">' + city.Text + '</option>');
                        });
                    },
                    error: function (ex) {
                        alert("Failed To Receive States" + ex);
                    }
                });  
            }
        });
    });
</script>

Upvotes: 0

Views: 1156

Answers (2)

CSharper
CSharper

Reputation: 5580

@Html.DropDownListFor(x => x.LeagueId, Model.LeagueSL, "--Select League--", new { id = "ddlLeague"})

@Html.DropDownListFor(x => x.LeagueId, Model.DivisionSL, "--Select Division--", new { id = "ddlDivision"})

The Second DropDownList is empty, all it has is the option Label --Select Division--

On change event of the 1st dropdown make an AjaxRequest that fills the Second One.

        var value = $("#DropDown1").val();
        var ddlDivision = $("#DropDownDivision");
            ddlDivision.html('');//clear current contents; 
 $.ajax({
            url: "/Home/GetDivisions",
            type: "GET",
            data: { leagueId: value },
            success: function (data) {

                $.each(data, function (index, item) {
                    //item = this        
                    //populate ddl                                          
                    ddlDivision.append($('<option></option>')
                   .val(item.PropTwo)
                   .html(item.PropOne));
                });
        });

        public JsonResult GetDivisions(int leagueId)
        {    
            using (BaseballEntities context = new BaseballEntities())
            {

                var divisions = (from x in context.Table
                                 where x.LeagueID == leagueId
                                 select new 
                                 {  
                                   PropOne = x.DivisionName,
                                   PropTwo = x.DivisionId
                                 }).ToList();


                return Json(divisions, JsonRequestBehavior.AllowGet);
            }            
        }

Edit: As a Side Note it is better to use your Model to fill your dropdownList. Give your model a SelectList property

 public List<SelectListItem> LeagueSL { get; set; }//you will need to initialize in constructor

 public ActionResult Index()
 {
             MyViewModel model = new MyViewModel();

              using (MyEntities context = new MyEntities())
             {
                var leagueList = context.League.ToList();

                foreach (var item in leagueList)
                {
                   model.LeagueSL.Add(new SelectListItem() { Text = item.LeagueName, Value = item.LeagueId.ToString() });
                }

             }
        return View(model);
    }

Upvotes: 1

Greg Burghardt
Greg Burghardt

Reputation: 18868

Drop down lists are their own beast. You probably need to create the new OPTIONs using standard DOM methods inside the loop rather than jQuery's append method:

                success: function(response) {
                    var items = "", option, $city = $("#City");
                    $.each(response, function(i, city) {
                        option = document.createElement("option");
                        option.value = city.Value;
                        option.innerHTML = city.Text;
                        $city.append(option);
                    });
                },

Upvotes: 1

Related Questions