MVC中DropDownList的问题

时间:2011-06-14 12:35:32

标签: asp.net-mvc model-view-controller drop-down-menu viewdata

`//View <tr><td>Experience level</td><td><div class="editor-field">
                    <%: Html.DropDownListFor(model => model.ExperienceLevelID, (SelectList)ViewData["Experience"], "--select--")%>
                    <%: Html.ValidationMessageFor(model => model.ExperienceLevelID) %>
                </div></td></tr>`<tr><td>Size of Company</td><td><div class="editor-field">

                <%: Html.DropDownList("Value", (SelectList)ViewData["size"], "--select--")%>

 public ActionResult Create()//Controller
    {
        ViewBag.mode = "create";IExperienceLevelRepository expLevelResp = new ExperienceLevelRepository();
        IQueryable<ExperienceLevel> expLevel = expLevelResp.GetAllExperienceLevels().OrderBy(ExperienceLevel => ExperienceLevel.Name);
        ViewData["Experience"] = new SelectList(expLevel, "ID", "Name");


        IEnumerable<SelectListItem> companySizes = new List<SelectListItem>
                                             {

                                                 new SelectListItem
                                                     {
                                                       Text = "Large Company",
                                                          Value = "large"

                                                     }
                                             };
        ViewData["size"] = new SelectList(companySizes, "Value", "Text");



        return View();
    } 

上面的下拉列表适用于ViewData [“体验”]但它不适用于大小,我必须手动硬编码下拉列表的大小,体验下拉列表从db填充。我得到的大小下拉列表的错误是:没有类型为'IEnumerable'的ViewData项具有键'Value'。

任何帮助或建议都将受到高度赞赏。

2 个答案:

答案 0 :(得分:3)

我强烈建议您使用视图模型和强类型视图而不是ViewData和弱类型帮助程序,因为它们缺少Intellisense并且是许多错误和丑陋视图的来源。

型号:

public class MyViewModel
{
    [Required]
    public string SelectedExperienceId { get; set; }
    public IEnumerable<SelectListItem> Experiences { get; set; }

    [Required]
    public string SelectedSizeId { get; set; }
    public IEnumerable<SelectListItem> Sizes { get; set; }
}

控制器:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        Experiences = new[]
        {
            new SelectListItem { Value = "exp1", Text = "Experience 1" },
            new SelectListItem { Value = "exp2", Text = "Experience 2" },
            new SelectListItem { Value = "exp3", Text = "Experience 3" },
        },
        Sizes = new[]
        {
            new SelectListItem { Value = "s1", Text = "Size 1" },
            new SelectListItem { Value = "s2", Text = "Size 2" },
            new SelectListItem { Value = "s3", Text = "Size 3" },
        }
    };
    return View(model);
}

强类型视图:

<%@ Page 
    Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master"     
    Inherits="System.Web.Mvc.ViewPage<AppName.Models.MyViewModel>" 
%>

...    

<%= Html.DropDownListFor(
    x => x.SelectedExperienceId,
    new SelectList(Model.Experiences, "Value, "Text"),
    "-- Experience --"
) %>
<%= Html.ValidationMessageFor(x => x.SelectedExperienceId) %>

...

<%= Html.DropDownListFor(
    x => x.SelectedSizeId,
    new SelectList(Model.Sizes, "Value, "Text"),
    "-- Size --"
) %>
<%= Html.ValidationMessageFor(x => x.SelectedSizeId) %>

现在剩下的就是将硬编码的值替换为来自数据库的值,方法是将存储库中返回的结果集映射到IEnumerable<SelectListItem>

答案 1 :(得分:1)

这为您提供了两种将项添加到SelectListItem列表的方法。您可以绑定现有集合,也可以手动填充它。

public List<SelectListItem> GetSomeSelectList()
{
  var items = SomeCollection
              .OrderByDescending(s => s.SomeProperty)
              .Select(s => new SelectListItem { 
                 Value = s.SomeProperty, 
                 Text = s.SomeOtherProperty })
              .ToList();
  items.Insert(0, new SelectListItem { Value = "0", Text = "Some Default" });
  return items;
}

我同意Darin你应该使用视图模型而不是viewdata。在我的例子中,我将上述方法放入视图模型中,在我看来,我调用了该方法。

<%: Html.DropDownListFor(m => m.SomeProperty, Model.GetSomeSelectList()) %>