asp.net-mvc mvc c# html.dropdownlist 和 viewbag

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12112541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:12:46  来源:igfitidea点击:

mvc c# html.dropdownlist and viewbag

asp.net-mvchtml.dropdownlistforviewbaghtml-select

提问by gdubs

So I have the following (pseudo code):

所以我有以下(伪代码):

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;

on my view:

在我看来:

<%: Html.DropDownList("Codes", (List<SelectListItem>)ViewBag.ListOfCodes , new { style = "max-width: 600px;" })%>

now, before it reaches the view, the "list" has populated it with items and has marked the item which is already selected. but when it gets to the view, none of the options are marked as selected.

现在,在它到达视图之前,“列表”已经用项目填充它并标记了已经选择的项目。但是当它进入视图时,没有一个选项被标记为选中。

my question is, is it possible to use a viewbag to pass the items or should i use a different medium? as it removes the selected flag on the options if i use it that way.

我的问题是,是否可以使用查看袋来传递物品,还是应该使用不同的媒介?因为如果我那样使用它,它会删除选项上的选定标志。

回答by Darin Dimitrov

Try like this:

像这样尝试:

ViewBag.ListOfCodes = new SelectList(mymodelinstance.Codes, "Id", "Name");
ViewBag.Codes = "C";

and in your view:

在您看来:

<%= Html.DropDownList(
    "Codes", 
    (IEnumerable<SelectListItem>)ViewBag.ListOfCodes, 
    new { style = "max-width: 600px;" }
) %>

For this to work you obviously must have an item with Id = "C" inside your collection, like this:

为此,您显然必须在您的收藏中拥有一个 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");