0

I have a MVC3 project (using C#) and am using Razor and EntityFramework 4.1 and I'd like to accomplish the following:

  1. Create a dropdown that displays provinces. Once you choose a province, it automatically populates a second dropdown that shows the cities under that province.
  2. A second dropdown that shows the cities (as populated by the first dropdown), once the user chooses the city, it will automatically populate a table showing the suburbs under the city.
  3. A table that contains a list of suburbs (based on the second dropdown).

Thanks in advance!

I've created my models,

public class Provinces
{
[Key]
public int ProvinceID {get; set;}
public string Province {get; set;}
public virtual ICollection<City> City {get;set;}
}

public class City
{
[Key]
public int CityID {get; set;}
public string City {get; set;}
public virtual ICollection<Suburb> Suburb {get; set;}
public virtual Province Province {get; set;}
}

public class Suburb
{
[Key]
public int SuburbID {get; set;}
public string Suburb {get; set;}
public virtual City City {get; set;}
}

A ViewModel to handle the dropdown

public class MyViewModel
{
public string SelectedProvinceID {get; set;}
public string SelectedCityID {get; set;}
public IEnumerable<Province> Province {get; set;}
}

A Controller

public class Suburbs : Controller
{
MyEntities suburbsDB = new MyEntities();

public ActionResult Create()
{ 
//For Province dropdown
ViewBag.Province = suburbsDB.Province.OrderBy(prov => prov.Province).ToList();

var suburbDetails =  new Suburb();
return View(suburbDetails);
}

I'm quite new to EntityFramework, Json, and Razor and I'm having a problem on how will I create the view. I've referenced the answer in Cascading drop-downs in MVC3 Razor view Cascading drop-downs in MVC 3 Razor view

How can I refresh the table based on the value of the Suburb dropdown?

Community
  • 1
  • 1
ryumang
  • 1
  • 2
  • 5
    So what do you have so far? Have you encountered some specific problems you would like to ask about when you tried to implement this? As right now it seems like you are posting your customer/teacher/boss requirements and expecting someone doing the project for you which is unlikely to happen. – Darin Dimitrov May 02 '11 at 06:16
  • 1
    Sounds like GiveMeSomeCodesPlz, I'm voting to close. – Ladislav Mrnka May 02 '11 at 08:13

2 Answers2

0

It's a little old now, but check out this article by Stephen Walther doing exactly this:

http://stephenwalther.com/blog/archive/2008/09/07/asp-net-mvc-tip-41-creating-cascading-dropdown-lists-with-ajax.aspx

He creates two dropdowns and uses jQuery/Ajax to fetch a list to populate the second one when a value is selected in the first one (you could easily extend this to have a third dropdown):

Click through to the article for the full code, but here's a snippet showing some of the significant javascript (I've added some comments):

function pageLoad() {
    ddlMakes = $get("Makes");
    ddlModels = $get("Models");
    // Bind the "bindOptions" function to the change event of the ddlMakes dropdown
    $addHandler(ddlMakes, "change", bindOptions);
    // Call the function immediately, so the next dropdown will be populated if there is already something selected in the first
    bindOptions();
}

function bindOptions() {
    // Clear out existing options in the second dropdown
    ddlModels.options.length = 0;
    // If something is selected in the first dropdown
    var makeId = ddlMakes.value;
    if (makeId) {
        // Send an ajax request to the corresponding url
        var url = "/Action/Models/" + makeId;
        getContent(url, bindOptionResults);
    }
}

function bindOptionResults(data) {
    var newOption;
    // Loop through the options in the response
    for (var k = 0; k < data.length; k++) {
        // Add a new option to the second dropdown for this item
        newOption = new Option(data[k].Name, data[k].Id);
        ddlModels.options.add(newOption);
    }
}
Danny Tuppeny
  • 40,147
  • 24
  • 151
  • 275
0

In your view, you'd define your two dropdowns, similar to this:

@Html.DropDownListFor(model => model.Provinces.ProvinceID, Model.Province, new { id = "ddlProvinces", onChange = "$:populateCitiesDropdown()" })

@Html.DropDownListFor(model => model.City.CityID, Model.City, new { id = "ddlCities" })

In Javascript, your populate method would look like this:

function populateIssuesDropdown() {
    $("#ddlCities").empty();
    var typeID = getProvinceID();
    $.getJSON('@Url.Action("GetCitiesByProvince", "some_controller")?TypeID=' + typeID, function (result) {
        $.each(result, function () {
            $("<option>").attr("value", this.CityID).text(this.City).appendTo("#ddlCities");
        });
    });
}

function getProvinceID() {
    var provinceID = $("#ddlProvinces").val();
    return provinceID;
}

In your Controller:

public JsonResult GetCitiesByProvince(int ProvinceID)
{
    var result = _someRepository.GetCities(ProvinceID).Select(
            c => new { CityID = c.CityID, City = c.City }); 
    JsonResult jsonResult = new JsonResult { Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

    return jsonResult;
}
WEFX
  • 8,298
  • 8
  • 66
  • 102