我完全混淆了许多关于使用html helper生成下拉列表的文章和教程。 我的目标是在我需要一个国家列表的第一个下拉2下拉,然后在选择一个国家后,下一个下拉列表显示该国家可用的旅行。 但是我陷入了第一次下降。
我创建了一个这样的模型
public class test
{
public List<Country> Countries { get; set; }
}
在我的控制器中我有这个
{
var country = db.Countries.ToList();
var vn = new test { Countries = country.ToList() };
return View(vn);
}
并且在视图中foreach
循环正常工作并显示国家/地区列表,但我的下拉列表中有错误,我真的很困惑如何修复它。
@model vidiaweb_com.Models.test
<div class="container" id="ttitle">
<nav class="">
<ul class="resetpadmar">
@foreach (var t in Model.Countries)
{
<li class="">
<div class="col-md-2 col-sm-2">
@t.CountryName
</div>
</li>
}
</ul>
</nav>
<div class="form-group">
@Html.LabelFor(model => model.Id, "Id", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Id", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
</div>
</div>
感谢任何帮助
答案 0 :(得分:2)
如果您没有看到加载的数据,那是因为您没有提供任何数据。您应该更改下拉列表,如下所示:
@Html.DropDownList("Id",
Model.Countries.Select(m => new SelectListItem
{
Value = m.Id.ToString(),
Text = m.Name
}),
new { @class = "form-control" })
甚至更好,使用强类型版本DropDownListFor
:
@Html.DropDownListFor(m => m.Id,
Model.Countries.Select(m => new SelectListItem
{
Value = m.Id.ToString(),
Text = m.Name
}),
new { @class = "form-control" })
注意: Text = m.Name
应更改为与您的模型相匹配。
答案 1 :(得分:1)
您需要的是mvc中的级联下拉列表
您的代码应该使用JQuery
在客户端完成,类似这样
$(function() {
$('#CountryId').change(function() {
var countrySelected = $('#CountryId:selected').val();
countrySelected = countrySelected == "" ? 0 : countrySelected;
//When select 'optionLabel' we need to reset it to default as well. So not need
//travel back to server.
if (countrySelected == "") {
$('#TourId').empty();
$('#TourId').append('<option value="">--Select a Tour--</option>');
return;
}
// call the method on the server to get all related trips
$.ajax({
type: "POST",
url: '@Url.Action("YourActionName","ControllerName")',
data: {
'countryId': countrySelected
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
var tourControl = $('#TourId');
if (result != null) {
tourControl.empty();
$.each(result.tours, function(index, data) {
// Here assuming that the value of tour is "Id" and display name is "Name"
tourControl.append('<option value="' + data.Id + '">' + data.Name + '</option>');
});
}
}
});
});
});
并在您的控制器中
[HttpPost]
public ActionResult YourActionName(int countryId)
{
var details = db.Tours.Where(t=>t.CountryId ==countryId);
return Json(new {tours = details});
}
here可下载样本的完整说明
希望这会对你有所帮助