Controller:
public ActionResult Filter()
{
ViewBag.Accounts = BusinessLayer.AccountManager.Instance.getUserAccounts(HttpContext.User.Identity.Name);
return View();
}
View:
<td>Account: </td>
<td>@Html.DropDownListFor("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))</td>
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?
Use Viewbag is wrong for sending list to view.You should using Viewmodel in this case. like this:
Send Country list and City list and Other list you need to show in View:
HomeController Code:
Viewmodel Code:
View Code:
..... .....
Country_Repository Code:
Try using
@Html.DropDownList
instead:@Html.DropDownListFor
expects a lambda as its first argument, not astring
for the ID as you specify.Other than that, without knowing what
getUserAccounts()
consists of, suffice to say it needs to return some sort of collection (IEnumerable
for example) that has at least 1 object in it. If it returnsnull
the property in the ViewBag won't have anything.You cannot used the Helper
@Html.DropdownListFor
, because the first parameter was not correct, change your helper to:@Html.DropDownListFor
receive in the first parameters a lambda expression in all overloads and is used to create strongly typed dropdowns.Here's the documentation
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
hope it will work
Here
String.Empty
will be the empty as a default selector.I do the following
In my action method
In my View Code
Try:
In the controller:
In the View:
or you can replace the "null" with whatever you want display as default selector, i.e. "Select Account".