MVC C#html.dropdownlist和viewbag [英] mvc c# html.dropdownlist and viewbag

查看:682
本文介绍了MVC C#html.dropdownlist和viewbag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有以下的(伪code):

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;

这是我的看法:

<%: 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.

我的问题是,是否有可能使用viewbag通过的项目或者我应该使用不同的媒介?因为它消除了选择标记的选择,如果我使用这种方式。

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.

推荐答案

尝试这样的:

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的项目您的收藏里面,像这样的:

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

    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");

这篇关于MVC C#html.dropdownlist和viewbag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆