Hi friends I want to develop a registration page int that page two fields 1.state 2.district(both are drop开发者_如何学Python down lists). now my question is how get data dynamically that is if select state field it will display all states available. for example there are three states 1.A 2.B 3.C each state contains 4 districts
state district1 district1 district1 district1
A AAA1 AAA2 AAA3 AAA4
B BBB1 BBB2 BBB3 BBB4
c CCC1 CCC2 CCC3 CCC4
if I select state A it has to display only state a districts
pls tell me clearly how to do it in asp.net
As always you start by defining a view model:
public class MyViewModel
{
[Required]
[DisplayName("Select a state:")]
public string SelectedState { get; set; }
public IEnumerable<SelectListItem> States { get; set; }
[Required]
[DisplayName("Select a district:")]
public string SelectedDistrict { get; set; }
public IEnumerable<SelectListItem> Districts { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// TODO: load the states initially
States = new[] { "A", "B", "C" }.Select(x => new SelectListItem
{
Value = x,
Text = x
}),
// Initially we don't have districts
Districts = Enumerable.Empty<SelectListItem>()
};
return View(model);
}
public ActionResult Districts(string state)
{
// TODO: given a state select its districts
var districts = Enumerable
.Range(1, 4)
.Select(x => string.Format("district {0} of state {1}", x, state));
return Json(districts, JsonRequestBehavior.AllowGet);
}
}
then a view:
@model MyViewModel
<div>
@Html.LabelFor(x => x.SelectedState)
@Html.DropDownListFor(
x => x.SelectedState,
Model.States,
"-- State --",
new {
id = "states",
data_url = Url.Action("districts")
}
)
</div>
<div>
@Html.LabelFor(x => x.SelectedDistrict)
@Html.DropDownListFor(
x => x.SelectedDistrict,
Model.Districts,
"-- District --",
new { id = "districts" }
)
</div>
and finally some javascript to cascade the States
dropdown:
$(function () {
$('#states').change(function () {
var url = $(this).data('url');
var selectedState = $(this).val();
$.get(url, { state: selectedState }, function (districts) {
var districtsDdl = $('#districts');
districtsDdl.empty();
$.each(districts, function (index, district) {
districtsDdl.append(
$('<option/>', {
value: district,
text: district
})
);
});
});
});
});
精彩评论