Reputation: 2629
I'm passing a Model into my view (.net mvc 3) that can't contain the information that I want to use to populate my drop down list.
I've never used Html.DropDownListFor() but have always just used Html.DropDownList(). I want to add another tool to my bag of tricks though and so want to try and incorporate Html.DropDownListFor().
Is it possible to use this helper with Key/Value pair set in a ViewBag variable?
Please advise, any code samples would be greatly appreciated (both front end (razor) and back end (on controller)).
TIA
Upvotes: 0
Views: 874
Reputation: 1038810
Is it possible to use this helper with Key/Value pair set in a ViewBag variable?
Absolutely not. If you want to use strongly typed helpers such as Html.DropDownListFor you need a view model. And since I always recommend using a view model, here's an example:
public class MyViewModel
{
public string SelectedId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
As you can see in this sample view model, for each dropdown you need 2 properties: a scalar property that will hold the selected value and a collection of SelectListItem
that will hold the options where each option consists of a value and text.
Then it's the controller's responsibility to initialize this view model and pass it to the view:
public ActionResult Index()
{
var model = new MyViewModel();
// normally those values will be dynamic. They will be mapped
// to the view model
model.Items = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
};
return View(model);
}
and then you will have a corresponding strongly typed view to this view model in which you will be able to use the strongly typed version of the helpers:
@model MyViewModel
@Html.DropDownListFor(x => x.SelectedId, Model.Items)
The following sentence from your question deserves some attention:
I'm passing a Model into my view (.net mvc 3) that can't contain the information that I want to use to populate my drop down list.
You should not be passing a model to a view. You should be passing a view model. A view model is a class that you specifically define for each view. It will contain the necessary information that this view will require. So a single view model could be composed from multiple models simply because such are the requirements of your view.
Upvotes: 1