C# 填充MVC Html.DropDownList的问题
我试图用一本字典的内容制作一个下拉列表,如下所示:C# 填充MVC Html.DropDownList的问题,c#,asp.net-mvc,C#,Asp.net Mvc,我试图用一本字典的内容制作一个下拉列表,如下所示: public static readonly IDictionary<string, string> VideoProviderDictionary = new Dictionary<string, string> { {"1", "Atlantic"}, {"2", "Blue Ridge"},
public static readonly IDictionary<string, string> VideoProviderDictionary = new Dictionary<string, string>
{
{"1", "Atlantic"},
{"2", "Blue Ridge"},
...
问题在于标记中,对于采用lambda表达式的DropDownList,没有重载:
@Html.DropDownList(Model -> model.Items)
我尝试使用:
@Html.DropDownListFor(model => model.Items)
但我得到了一个错误:
CS1501: No overload for method 'DropDownListFor' takes 1 arguments
控制器:
[HttpGet]
public ActionResult Register()
{
var model = new RegisterViewModel();
Viewbag.Items = new SelectList(VideoProviders.VideoProviderDictionary);
......
......
return View(model);
}
视图:
@Html.DropDownList("VideoProvider",Viewbag.Items as SelectList)
或者,对于强类型dropdownlist,请执行以下操作:
@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.
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; }
}
publicstringvideoprovider{get;set;}//请在此处更正
public IEnumerable Items{get;set;}//如果您使用Viewbag绑定dropdownlist(这是MVC中最简单有效的方法),那么您不需要任何用于下拉的模型属性,您可以删除此属性。
在您的情况下-
型号:
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.
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; }
}
视图:
编译器错误消息:CS1501:方法“DropDownListFor”没有重载需要1个参数在我将您的anser标记为正确之前,它会将列表中的每个项目显示为[1-Comcast],等等。如何修改控制器代码以使其仅为Comcast或字典中的任何值?我知道了。我只是设定了它的值。Thanks@user2471435我不明白这个答案。那么,您想返回“Items”属性中的值吗?@user2471435..很抱歉,我今天的互联网连接不好。。只需在model和dropdownlist中查看更新的答案和更正的小问题…model property VideoProvider将在post controller上选择下拉值。。谢谢
[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)