I would like to have small example screen which should have two combo. First one should display the 开发者_StackOverflow社区name of the countries from country table and upon selecting the country name in the combo, next combo should be displayed with the district name.
Country Table structure:
Country Name,
Country Id
District table structure.
District id
Country id
District name
Anybody can help me?
it's kinda easy...
the 1st dropdown is easy, just pass the IEnumerable
in the model and voilá.
the 2nd dropdown is as easy but just takes a little bit more code:
all you need to do is to call a method and send the value of the first dropdown, then in your method, just call the DB and return a JsonResult
example:
<select id="dropdown1">
<option value="" selected="true">Select country</option>
<% foreach(var country in Model.Countries) { %>
<option value="<%= country.Id %>"><%= country.Name %></option>
<% } %>
</select><br/>
<select id="dropdown2"></select>
at the end of the page
<script>
$(document).ready( function() {
$("#dropdown1").bind("change", function() {
// everytime the value of the dropdown 1 is changed, do this:
var countryId = $("#dropdown1").val();
$.get("/country/getDistricts", { 'country' : countryId }, function(data) {
$("#dropdown2").empty(); // clear old values if exist
var options = "";
for(i = 0; i < data.length; i++) { // build options
options += ("<option value='" + data[i].districtId + "'>" + data[i].districtName + "</option>");
}
$("#dropdown2").append(options);
});
});
});
</script>
in your Action at country
Controller
public ActionResult getDistricts(string country)
{
List<Districts> districts = dbRepository.GetDistrictsByCountryId(country);
return Json(districts, JsonRequestBehavior.AllowGet);
}
There are two possible ways to achieve this.
Either put all combinations in html and use javascript to change the contents of the second combo upon selection in first combo.
Or setup AutoPostback on the first combo and fill the second one at server-side depending on the selected value of first combo.
精彩评论