C# 用另一个列表框填充MVC 4列表框
我需要一种方法来说明如何根据同一视图中另一个列表框中的选定值填充视图中的列表框 例如,我需要一个城市列表框,其中包含在另一个列表框中选择的国家名称C# 用另一个列表框填充MVC 4列表框,c#,asp.net-mvc-4,model-view-controller,listbox,C#,Asp.net Mvc 4,Model View Controller,Listbox,我需要一种方法来说明如何根据同一视图中另一个列表框中的选定值填充视图中的列表框 例如,我需要一个城市列表框,其中包含在另一个列表框中选择的国家名称 thx提前,抱歉我的英语在home controller中,我决定使用集合初始值设定项来建立国家列表,但更重要的是,我觉得通过使用ViewBag dynamic over ViewData,代码更干净 public ActionResult Index() { var countries = new List<strin
thx提前,抱歉我的英语在home controller中,我决定使用集合初始值设定项来建立国家列表,但更重要的是,我觉得通过使用ViewBag dynamic over 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>
}
您好,我已经安装了Json包,但在参考资料中看不到它。。。我使用浏览器直接引用它,但是JsonResult类型没有出现…我已经能够使用JsonResult,但是返回Json。。。他穿着灰色的衣服。。它说Json这个名字在当前上下文中不存在。Json现在它在上下文中,我不得不添加@using System.Web.Helpers,但现在的问题是它说Json是一种类型,它被当作变量使用。最后我解决了这个问题,我在一个非从controller派生的类中使用了该代码。如果它对您有帮助,请将其标记为答案,否则请发布答案