Question

for some reason does not work for me a simple application. Can somebody check what I'm doing wrong? Country and status is good, but the list of animals is always empty.

View

@{
    ViewBag.Title = "Classic Cascading DDL";
}

@using (Html.BeginForm("IndexDDL", "Home", FormMethod.Post, 
    new { id = "CountryStateFormID",
          data_stateListAction = @Url.Action("StateList"),
          data_petListAction = @Url.Action("PetList")
    }))
{
    <fieldset>
        <legend>Country/State</legend>
        @Html.DropDownList("Countries", ViewBag.Country as SelectList,
            "Select a Country", new { id = "CountriesID" })
        <div id="StatesDivID" >
            <label for="States">States</label>
            <select id="StatesID"  name="States"></select>
        </div>
        <div id="PetsDivID">
            <label for="Pets">Pets</label>
            <select id="PetsID"  name="Pets"></select>
        </div>

        <p>
            <input type="submit" value="Submit" id="SubmitID" />
        </p>
    </fieldset>
}

<script src="@Url.Content("~/Scripts/countryState.js")"></script>

Model: Country

using System.Collections.Generic;
using System.Linq;

namespace CascadingDDL.Models {
    public class Country {
        public string Code { get; set; }
        public string Name { get; set; }

        public static IQueryable<Country> GetCountries() {
            return new List<Country>
            {
                new Country {
                    Code = "CA",
                    Name = "Canada"
                },
                new Country{
                    Code = "US",
                    Name = "United States"
                },
                new Country{
                    Code = "UK",
                    Name = "United Kingdom"
                }
            }.AsQueryable();
        }
    }
}

Model: State

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CascadingDDL.Models {
    public class State {
        public string Code { get; set; }
        public string CodePet { get; set; }
        public int StateID { get; set; }
        public string StateName { get; set; }
        static int cnt = 0;  

        public static IQueryable<State> GetStates() {
            cnt = 0;
            return new List<State>
            {
                 new State
                    {
                        Code = "CA",
                        CodePet ="CAT",
                        StateID=cnt++,
                        StateName = "Nunavut"
                    },
                new State
                    {
                        Code = "CA",
                        CodePet ="DOG",
                        StateID=cnt++,
                        StateName = "Ontario"
                    },
                new State
                    {
                        Code = "US",
                        CodePet ="DOG",
                        StateID=cnt++,
                        StateName = "Washington"
                    },
                new State
                    {
                        Code = "US",
                        CodePet ="DOG",
                        StateID=cnt++,
                        StateName = "Vermont"
                    },
                    new State
                    {
                        Code = "UK",
                        CodePet ="DOG",
                        StateID=cnt++,
                        StateName = "Britian"
                    },
                     new State
                    {
                        Code = "UK",
                        CodePet ="DOG",
                        StateID=cnt++,
                        StateName = "Northern Ireland"
                    },
                     new State
                    {
                        Code = "UK",
                        CodePet ="DUCK",
                        StateID=cnt++,
                        StateName = "Scotland"
                    },
                         new State
                    {
                        Code = "UK",
                        CodePet ="DUCK",
                        StateID=cnt++,
                        StateName = "Wales"
                    }
            }.AsQueryable();
        }
    }
}

Model: Pet

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CascadingDDL.Models {
    public class Pet {
        public string CodePet { get; set; }
        public int PetID { get; set; }
        public string PetName { get; set; }
        static int cnt = 0; 

        public static IQueryable<Pet> GetPets() {
            cnt = 0;
            return new List<Pet>
            {
                 new Pet
                    {
                        CodePet = "CAT",
                        PetID=0, 
                        PetName = "Cat-1"
                    },
                new Pet
                    {
                        CodePet = "DOG",
                        PetID=1,
                        PetName = "Dog-1"
                    },
                new Pet
                    {
                        CodePet = "DUCK",
                        PetID=2,
                        PetName = "Duck-1"
                    }
            }.AsQueryable();
        }
    }
}

Part of the controller

public ActionResult StateList(string ID) {
    string Code = ID;
    var states = from s in State.GetStates()
                 where s.Code == Code
                 select s;

    if (HttpContext.Request.IsAjaxRequest())
        return Json(new SelectList(
                        states.ToArray(),
                        "StateID",
                        "StateName")
                   , JsonRequestBehavior.AllowGet);

    return RedirectToAction("Index");
}

public ActionResult PetList(string ID)
{
    string CodePet = ID;
    var pets = from s in Pet.GetPets()
                 where s.CodePet == CodePet
                 select s;

    if (HttpContext.Request.IsAjaxRequest())
        return Json(new SelectList(
                        pets.ToArray(),
                        "PetID",
                        "PetName")
                   , JsonRequestBehavior.AllowGet);

    return RedirectToAction("Index");
}

Script

$(function () {

    $('#StatesDivID').hide();
    $('#PetsDivID').hide();
    $('#SubmitID').hide();

    $('#CountriesID').change(function () {
        var URL = $('#CountryStateFormID').data('stateListAction');
        $.getJSON(URL + '/' + $('#CountriesID').val(), function (data) {
            var items = '<option>Select a State</option>';
            $.each(data, function (i, state) {
                items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
            });
            $('#StatesID').html(items);
            $('#StatesDivID').show();
        });
    });

    $('#StatesID').change(function () {
        var URL = $('#CountryStateFormID').data('petListAction');
        $.getJSON(URL + '/' + $('#StatesID').val(), function (data) {
            var items = '<option>Select a Pet</option>';
            $.each(data, function (i, pet) {
                items += "<option value='" + pet.Value + "'>" + pet.Text + "</option>";
            });
            $('#PetsID').html(items);
            $('#PetsDivID').show();
        });
    });
});

No matter what state I choose always "Select a Pet"

Was it helpful?

Solution

If you want to retrieve the data you need to change this line in your StateList Action:

 if (HttpContext.Request.IsAjaxRequest())
     return Json(new SelectList(
                    states.ToArray(),
                    "StateID",
                    "StateName")
               , JsonRequestBehavior.AllowGet);

To:

  if (HttpContext.Request.IsAjaxRequest())
    return Json(new SelectList(
                    states.ToArray(),
                    "CodePet",
                    "StateName")
               , JsonRequestBehavior.AllowGet);

As in your PetList Action you need the CodePet for the filter not the StateId. I hope it will help

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top