所以我有以下(伪代码):
string selectedvalud = "C";
List<SelectListItem> list= new List<SelectListItem>();
foreach(var item in mymodelinstance.Codes){
list.Add(new SelectListItem { Text = item.Name, Value = item.Id.Tostring(), Selected = item.Id.ToString() == selectedvalue ? true : false });
}
ViewBag.ListOfCodes = list;
我的看法:
<%: Html.DropDownList("Codes", (List<SelectListItem>)ViewBag.ListOfCodes , new { style = "max-width: 600px;" })%>
现在,在到达 View 之前,“列表”已填充了项目并标记了已选择的项目。但是当它到达 View 时,没有任何选项被标记为已选择。
我的问题是,是否可以使用 View 袋来传递元素,或者我应该使用不同的媒介?因为如果我这样使用它,它会删除选项上选定的标志。
最佳答案
尝试这样:
ViewBag.ListOfCodes = new SelectList(mymodelinstance.Codes, "Id", "Name");
ViewBag.Codes = "C";
在您看来:
<%= Html.DropDownList(
"Codes",
(IEnumerable<SelectListItem>)ViewBag.ListOfCodes,
new { style = "max-width: 600px;" }
) %>
为此,您的集合中显然必须有一个 Id =“C”的项目,如下所示:
ViewBag.ListOfCodes = new SelectList(new[]
{
new { Id = "A", Name = "Code A" },
new { Id = "B", Name = "Code B" },
new { Id = "C", Name = "Code C" },
}, "Id", "Name");
关于asp.net-mvc - mvc c# html.dropdownlist 和 viewbag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12112541/