我需要一個方法如何在視圖中填充列表框取決於在同一視圖中的另一個列表框中的選定值。MVC 4列表框填充另一個列表框
例如,我需要一個城市列表框填充在另一個列表框中選擇的國家的名稱。
THX提前對不起我的英語
我需要一個方法如何在視圖中填充列表框取決於在同一視圖中的另一個列表框中的選定值。MVC 4列表框填充另一個列表框
例如,我需要一個城市列表框填充在另一個列表框中選擇的國家的名稱。
THX提前對不起我的英語
在家用控制器我已經決定使用集合初始建立的國家名單,但更重要的是我覺得代碼是通過使用ViewBag動態過ViewData的清潔劑。
public ActionResult Index()
{
var countries = new List<string> {"USA", "UK", "India"};
var countryOptions = new SelectList(countries);
ViewBag.Countries = countryOptions;
return View();
}
接下來是GetStates()操作方法。在這裏我做了一個改變,使我能夠通過HttpGet請求檢索狀態。原因是我相信HttpGet最適合這個請求,因爲我們只是從服務器檢索信息。如果我們正在添加或更新狀態,那麼將需要HttpPost請求。
public JsonResult GetStates(string country)
{
var states = new List<string>();
switch (country)
{
case "USA":
states.Add("California");
states.Add("Florida");
states.Add("Ohio");
break;
case "UK":
states.Add("London");
states.Add("Essex");
break;
case "India":
states.Add("Goa");
states.Add("Punjab");
break;
}
//Add JsonRequest behavior to allow retrieving states over http get
return Json(states, JsonRequestBehavior.AllowGet);
}
我的解決方案的第二部分也是最後一部分是Index.cshtml文件。在這個文件中,我有表單的html以及從服務器檢索狀態所需的javascript。
@using (Html.BeginForm())
{
<div>Select country:</div>
<div>@Html.DropDownList("country",
ViewBag.Countries as SelectList,
"Please select",
new { id = "country" })
</div>
<div>Select state:</div>
<div>
<select id="state" disabled="disabled"></select>
</div>
<input type="submit" value="Submit"/>
}
@section scripts
{
<script type="text/javascript">
$(function() {
$('#country').on('change', function() {
var stateDropdown = $('#state');
//disable state drop down
stateDropdown.prop('disabled', 'disabled');
//clear drop down of old states
stateDropdown.empty();
//retrieve selected country
var country = $(this).val();
if (country.length > 0) {
// retrieve data using a Url.Action() to construct url
$.getJSON('@Url.Action("GetStates")', {
country: country
})
.done(function (data) {
//re-enable state drop down
stateDropdown.removeProp('disabled');
//for each returned state
$.each(data, function (i, state) {
//Create new option
var option = $('>option /<').html(state);
//append state states drop down
stateDropdown.append(option);
});
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});
}
});
})
</script>
}
[MVC級聯下拉列表](https://www.google.com.au/search?q=mvc+cascading+dropdownlist&oq=mvc+cascad&aqs=chrome.1.69i57j69i59j69i60l2j69i59j0.4092j0j7&sourceid=chrome&espv=2&es_sm=122&ie = UTF-8) – 2014-10-31 08:19:55