Reputation: 1674
I am trying to poulate a DropDownList with the contents of a Dictionary which is like this:
public static readonly IDictionary<string, string> VideoProviderDictionary = new Dictionary<string, string>
{
{"1", "Atlantic"},
{"2", "Blue Ridge"},
...
For the model I have:
public string[] VideoProvider { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
In the controller, I am trying to populate the list:
[HttpGet]
public ActionResult Register()
{
var model = new RegisterViewModel();
model.Items = new SelectList(VideoProviders.VideoProviderDictionary);
return View(model);
}
The issue is in the markup, there is no overload for DropDownList that takes a lambda expression:
@Html.DropDownList(Model -> model.Items)
I tried to use:
@Html.DropDownListFor(model => model.Items)
But I get the error:
CS1501: No overload for method 'DropDownListFor' takes 1 arguments
Upvotes: 1
Views: 542
Reputation: 18873
Controller :
[HttpGet]
public ActionResult Register()
{
var model = new RegisterViewModel();
Viewbag.Items = new SelectList(VideoProviders.VideoProviderDictionary);
......
......
return View(model);
}
View :
@Html.DropDownList("VideoProvider",Viewbag.Items as SelectList)
OR For strongly typed dropdownlist do this :
@Html.DropDownListFor(model=>model.VideoProvider,Viewbag.Items as SelectList)
Model:
public string VideoProvider { get; set; } //Correct here
public IEnumerable<SelectListItem> Items { get; set; } //if you are using Viewbag to bind dropdownlist(which is a easiest and effective way in MVC) then you don't need any model property for dropdown,you can remove this property.
Upvotes: 0
Reputation: 4862
In your case -
Model:
public class RegisterViewModel
{
public static readonly IDictionary<string, string> VideoProviderDictionary = new Dictionary<string, string>
{{"1", "Atlantic"},
{"2", "Blue Ridge"}};
public string VideoProvider { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Controller:
[HttpGet]
public ActionResult Register() {
var model = new RegisterViewModel();
model.Items = new SelectList(RegisterViewModel.VideoProviderDictionary, "key", "value");
return View(model);
}
View:
@Html.DropDownListFor(model => model.VideoProvider, Model.Items)
Upvotes: 2