填充MVC Html.DropDownList的问题

本文关键字:问题 DropDownList Html MVC 填充 | 更新日期: 2023-09-27 18:19:31

我正试图用字典的内容放入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

填充MVC Html.DropDownList的问题

在您的案例中-

型号:

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)

控制器:

[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.