ASP.NET MVC 4允许用户选择州,然后加载城市 [英] ASP.NET MVC 4 Allow User to Select State and then load city
问题描述
我有3个班级和桌子
- 状态
- 城市
- 面积
StateId是FK到City Table,CityId是FK到Area
StateId is FK to City Table, CityId is FK to Area
在创建区域形式上,我想添加State DropDown.我正在ViewBag中发送状态列表,但不知道如何绑定它.同样,默认情况下,它会带动所有城市,大约100多个城市.我只想在状态更改时绑定城市,不希望模型在首次加载时从城市表中带走所有行.
On Create Form of Area I want to add State DropDown. I am sending State list in ViewBag, but don't know how to bind it. Also by default its bring all city with it, near about 100 plus I only want to bind city when state is changed, don't want model to bring all rows from city table when it first load.
预先感谢
推荐答案
我最近在博客中谈到了MVC4中的级联下拉列表,我想这就是您要追求的(尽管会提供更多细节).
I recently blogged about cascading dropdownlists in MVC4 which I think is what you are after (although a little more detail would be appreciated).
http://jnye.co/posts/12/creating-cascading-dropdownlists-using-mvc-4-and-jquery
本质上,在您的控制器中:
In essence, in your controller:
public ActionResult Index()
{
// These countries are equivalent to your states
var states = new List<string> {"Ohio", "California", "Florida"};
var stateOptions = new SelectList(states);
ViewBag.States = stateOptions;
return View();
}
public JsonResult GetCities(string state)
{
var cities = new List<string>();
switch (country)
{
case "Florida":
states.Add("City1");
states.Add("City2");
states.Add("City3");
break;
case "Ohio":
states.Add("City4");
states.Add("City5");
break;
case "California":
states.Add("City6");
states.Add("City7");
break;
}
//Add JsonRequest behavior to allow retrieving states over http get
return Json(cities, JsonRequestBehavior.AllowGet);
}
然后,在您看来:
@using (Html.BeginForm())
{
<div>Select state:</div>
<div>@Html.DropDownList("state",
ViewBag.States as SelectList,
"Please select",
new { id = "state" })
</div>
<div>Select City:</div>
<div>
<select id="city" disabled="disabled"></select>
</div>
<input type="submit" value="Submit"/>
}
@section scripts{
<script type="text/javascript">
$(function() {
$('#state').on('change', function() {
var cityDropdown = $('#city');
//disable city drop down
cityDropdown.prop('disabled', 'disabled');
//clear drop down of old city
cityDropdown.empty();
//retrieve selected state
var state = $(this).val();
if (state.length > 0) {
// retrieve data using a Url.Action() to construct url
$.getJSON('@Url.Action("GetCities")', {
state: state
})
.done(function (data) {
//re-enable city drop down
cityDropdown.removeProp('disabled');
//for each returned state
$.each(data, function (i, city) {
//Create new option
var option = $('<option />').html(city);
//append city states drop down
cityDropdown.append(option);
});
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});
}
});
})
</script>
}
这篇关于ASP.NET MVC 4允许用户选择州,然后加载城市的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!