如何使用ViewBag创建下拉列表? [英] How to use a ViewBag to create a dropdownlist?
问题描述
控制器:
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
包含具有AccountID
,AccountName
和其他属性的Account
对象.
我想要一个名为 accountid 的DropDownList
(这样在Form Post上我可以传递所选的AccountID)和DropDownList
来显示AccountName
,同时将AccountID
作为值.
ViewBag.Accounts
contains Account
objects which have AccountID
, AccountName
and other properties.
I would like a DropDownList
called accountid (so that on Form Post I can pass the selected AccountID) and the DropDownList
to display the AccountName
while having the AccountID
as value.
我在查看代码中做错了什么?
What am I doing wrong in the view code?
推荐答案
您不能使用Helper @Html.DropdownListFor
,因为第一个参数不正确,请将您的Helper更改为:
You cannot used the Helper @Html.DropdownListFor
, because the first parameter was not correct, change your helper to:
@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))
@Html.DropDownListFor
在所有重载中的第一个参数中都接收一个lambda表达式,并用于创建强类型的下拉列表.
@Html.DropDownListFor
receive in the first parameters a lambda expression in all overloads and is used to create strongly typed dropdowns.
如果您的View的类型是强类型的,则可以使用帮助程序来更改代码,以创建强类型的下拉列表,例如
If your View it's strongly typed to some Model you may change your code using a helper to created a strongly typed dropdownlist, something like
@Html.DropDownListFor(x => x.accountId, new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))
这篇关于如何使用ViewBag创建下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!