My difficulty is how to use ViewBag
with DropdownListFor
?
In my controller I am having:
TestModel model = new TestModel();
ViewBag.Clients = model.Clients;
ViewBag.StatusList = model.StatusList;
ViewBag.enumStatus = model.enumStatus;
ViewBag.intClient = model.intClient;
In my TestModel
public SelectList Clients { get; set; }
public SelectList StatusList { get; set; }
public ActiveStatus enumStatus { get; set; }
public int? intClient { get; set; }
In my View
I want to use DropDownListFor
to display the ViewBag values, how can I do that?
You could do this:
@Html.DropDownListFor(x => x.intClient, ViewBag.Clients)
But I would recommend you to avoid ViewBag/ViewData and profit from your view model:
public ActionResult Index()
{
var model = new TestModel();
model.Clients = new SelectList(new[]
{
new { Value = "1", Text = "client 1" },
new { Value = "2", Text = "client 2" },
new { Value = "3", Text = "client 3" },
}, "Value", "Text");
model.intClient = 2;
return View(model);
}
and in the view:
@Html.DropDownListFor(x => x.intClient, Model.Clients)
Personally...I create a List and do this.
public ActionResult SomeAction()
{
var list = new List<SelectListItem>();
list.Add(new SelectListItem(){Text = "One", Value="One"});
list.Add(new SelectListItem(){Text = "Two", Value="Two"});
list.Add(new SelectListItem(){Text = "Three", Value="Three"});
list.Add(new SelectListItem(){Text = "Four", Value="Four"});
ViewBag.Clients = list;
return View();
}
and then in your view...
@Html.DropDownListFor(x => x.SomePropertyOnModel, (IEnumerable<SelectListItem>)ViewBag.Clients);
Notice the cast on the Viewbag item. The cast is required because the viewbag has no idea what the object is for Viewbag.Client
. So the cast there is required.
@Html.DropDownListFor(x => x.intClient, new SelectList(Model.Clients, "ClientId", "ClientName"), string.Empty);
The ClientId is the value of the dropdown option.
The ClientName is the text of the dropdown option.
The string.Empty
at the end adds a blank entry to the dropdown.
Here you can find a good reference: http://blogs.msdn.com/b/nunos/archive/2010/02/08/quick-tips-about-asp-net-mvc-editor-templates.aspx