我正在尝试使用类似这样的字典内容来填充DropDownList:
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; }
在控制器中,我试图填充列表:
[HttpGet]
public ActionResult Register()
{
var model = new RegisterViewModel();
model.Items = new SelectList(VideoProviders.VideoProviderDictionary);
return View(model);
}
问题在于标记,DropDownList没有带有lambda表达式的重载:
@Html.DropDownList(Model -> model.Items)
我试图使用:
@Html.DropDownListFor(model => model.Items)
但我收到错误:
CS1501: No overload for method 'DropDownListFor' takes 1 arguments
答案 0 :(得分:2)
在你的情况下 -
型号:
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; }
}
控制器:
[HttpGet]
public ActionResult Register() {
var model = new RegisterViewModel();
model.Items = new SelectList(RegisterViewModel.VideoProviderDictionary, "key", "value");
return View(model);
}
查看:
@Html.DropDownListFor(model => model.VideoProvider, Model.Items)
答案 1 :(得分:0)
控制器:
[HttpGet]
public ActionResult Register()
{
var model = new RegisterViewModel();
Viewbag.Items = new SelectList(VideoProviders.VideoProviderDictionary);
......
......
return View(model);
}
查看:
@Html.DropDownList("VideoProvider",Viewbag.Items as SelectList)
或者对于强类型下拉列表,请执行以下操作:
@Html.DropDownListFor(model=>model.VideoProvider,Viewbag.Items as SelectList)
型号:
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.