首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用ViewBag创建下拉列表?

如何使用ViewBag创建下拉列表?
EN

Stack Overflow用户
提问于 2013-05-17 02:37:23
回答 7查看 176.8K关注 0票数 39

控制器:

public ActionResult Filter()
{
    ViewBag.Accounts = BusinessLayer.AccountManager.Instance.getUserAccounts(HttpContext.User.Identity.Name);
    return View();
}

查看:

<td>Account: </td>
<td>@Html.DropDownListFor("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))</td>

ViewBag.Accounts包含具有AccountIDAccountName和其他属性的Account对象。我想要一个名为accountidDropDownList (这样在Form Post上我可以传递选定的AccountID)和DropDownList来显示AccountName,同时具有AccountID作为值。

我在视图代码中做错了什么?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2013-05-17 03:02:21

不能使用帮助器@Html.DropdownListFor,因为第一个参数不正确,请将帮助器更改为:

@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))

@Html.DropDownListFor在第一个参数中接收所有重载中的λ表达式,并用于创建强类型的下拉列表。

Here's the documentation

如果你的视图是强类型的,你可以使用帮助器修改你的代码来创建一个强类型的下拉列表,类似于

@Html.DropDownListFor(x => x.accountId, new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))
票数 73
EN

Stack Overflow用户

发布于 2016-12-17 00:49:08

尝试:

在控制器中:

ViewBag.Accounts= new SelectList(db.Accounts, "AccountId", "AccountName");

在视图中:

@Html.DropDownList("AccountId", (IEnumerable<SelectListItem>)ViewBag.Accounts, null, new { @class ="form-control" })

或者,您可以将"null“替换为您希望显示为默认选择器的任何内容。“选择帐户”。

票数 21
EN

Stack Overflow用户

发布于 2013-05-17 02:55:16

我执行以下操作

在我的操作方法中

    Dictionary<string, string> dictAccounts = ViewModelDropDown.GetAccounts(id);
    ViewBag.accounts = dictAccounts;

在我的视图代码中

 Dictionary<string, string> accounts = (Dictionary<string, string>)ViewBag.accounts;
 @Html.DropDownListFor(model => model.AccountId, new SelectList(accounts, "Value", "Key"), new { style = "width:310px; height: 30px; padding 5px; margin: 5px 0 6px; background: none repeat scroll 0 0 #FFFFFF; vertical-align:middle;" })
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16594958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档