加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 23:16:41 所属栏目:asp.Net 来源:网络整理
导读:控制器: public ActionResult Filter(){ ViewBag.Accounts = BusinessLayer.AccountManager.Instance.getUserAccounts(HttpContext.User.Identity.Name); return View();} 视图: tdAccount: /tdtd@Html.DropDownListFor("accountid",new SelectList(ViewBa
控制器:
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"))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读