我遇到问题,让DropDownList正确选择正确的值并显示它。
我使用以下内容:
@Html.DropDownListFor(x => Model.AdminSummaries[index].Status, AdminStatusReference.GetAdminStatusOptions(), new { id = string.Format("Status_{0}",index ) })
AdminStatusReference.GetAdminStatusOptions()可以返回List还是必须返回IEnumerable?
答案 0 :(得分:2)
型号:
public class MyViewModel
{
public IList<AdminSummary> AdminSummaries { get; set; }
}
public class AdminSummary
{
public string Status { get; set; }
}
public static class AdminStatusReference
{
public static IEnumerable<SelectListItem> GetAdminStatusOptions()
{
return new[]
{
new SelectListItem { Value = "1", Text = "status 1" },
new SelectListItem { Value = "2", Text = "status 2" },
new SelectListItem { Value = "3", Text = "status 3" },
};
}
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
AdminSummaries = new[]
{
// preselect the first item
new AdminSummary { Status = "1" },
// preselect the second item
new AdminSummary { Status = "2" },
// nothing will be preselected because there is no xxx Value in the list
new AdminSummary { Status = "xxx" },
}.ToList()
};
return View(model);
}
}
查看:
@model MyViewModel
@for (int index = 0; index < Model.AdminSummaries.Count; index++)
{
@Html.DropDownListFor(
x => x.AdminSummaries[index].Status,
new SelectList(
AdminStatusReference.GetAdminStatusOptions(),
"Value",
"Text",
Model.AdminSummaries[index].Status
)
)
}
答案 1 :(得分:0)
没关系
List<T>
实施IEnumerable<T>
答案 2 :(得分:0)
使用
@Html.DropDownListFor<>
在我的项目中,我总是在我的视图中使用IEnumerable<SelectListItem>
,因此我手动设置哪个项目的属性为“已选择”为真。然后,这将设置默认项目。
忘了我可以编辑我的原始答案:P 这是在我的项目中呈现的html