rik*_*ket 32 asp.net-mvc viewbag dropdownlistfor
控制器:
public ActionResult Filter()
{
ViewBag.Accounts = BusinessLayer.AccountManager.Instance.getUserAccounts(HttpContext.User.Identity.Name);
return View();
}
Run Code Online (Sandbox Code Playgroud)
视图:
<td>Account: </td>
<td>@Html.DropDownListFor("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))</td>
Run Code Online (Sandbox Code Playgroud)
ViewBag.Accounts包含Account具有的对象AccountID,AccountName以及其他属性.我想要一个DropDownList被调用的accountid(以便在Form Post上我可以传递所选的AccountID)并DropDownList显示AccountName具有AccountIDas值的while .
我在视图代码中做错了什么?
Jor*_*rge 64
您无法使用Helper @Html.DropdownListFor,因为第一个参数不正确,请将您的帮助器更改为:
@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))
Run Code Online (Sandbox Code Playgroud)
@Html.DropDownListFor 在第一个参数中接收所有重载中的lambda表达式,并用于创建强类型下拉列表.
如果您对某个模型强烈键入View,则可以使用帮助程序更改代码以创建强类型下拉列表,类似于
@Html.DropDownListFor(x => x.accountId, new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))
Run Code Online (Sandbox Code Playgroud)
小智 12
尝试:
在控制器中:
ViewBag.Accounts= new SelectList(db.Accounts, "AccountId", "AccountName");
Run Code Online (Sandbox Code Playgroud)
在视图中:
@Html.DropDownList("AccountId", (IEnumerable<SelectListItem>)ViewBag.Accounts, null, new { @class ="form-control" })
Run Code Online (Sandbox Code Playgroud)
或者您可以将"null"替换为您想要显示为默认选择器的任何内容,即"选择帐户".
我做以下
在我的行动方法中
Dictionary<string, string> dictAccounts = ViewModelDropDown.GetAccounts(id);
ViewBag.accounts = dictAccounts;
Run Code Online (Sandbox Code Playgroud)
在我的查看代码中
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;" })
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
136350 次 |
| 最近记录: |