asp.net-mvc – 如何使用ViewBag创建一个下拉列表?

控制器:
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为值.

代码中我做错了什么?

解决方法

你不能使用Helper @ Html.DropdownListFor,因为第一个参数是不正确的改变你的帮手:
@Html.DropDownList("accountid","AccountName"))

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

Here’s the documentation

如果您的查看它强大类型为某些模型,您可以使用帮助器更改您的代码,以创建一个强类型的下拉列表,像

@Html.DropDownListFor(x => x.accountId,"AccountName"))

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....