MVC 中 DropDownList 的问题

发布于 2024-11-15 08:51:05 字数 1768 浏览 2 评论 0原文

`//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["Experience"] 但它不适用于 size ,我必须手动对下拉列表进行硬编码以获取大小,并且体验下拉列表是从数据库填充的。我得到的大小下拉列表的错误是:没有具有键“Value”的“IEnumerable”类型的 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();
    } 

The above dropdownlist works fine for the ViewData["Experience"] But it doesnt works with size , I have to manually hardcode the dropdownlist for size and the experience dropdownlist is populated from db. The error which i m getting for size dropdownlist is :There is no ViewData item of type 'IEnumerable' that has the key 'Value'.

Any help or suggestions will be highly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

懷念過去 2024-11-22 08:51:05

我强烈建议您使用视图模型和强类型视图,而不是 ViewData 和弱类型帮助器,因为它们缺乏智能感知,并且是许多错误和丑陋视图的根源。

模型:

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,用来自数据库的值替换硬编码值。

I would very strongly recommend you to use view models and strongly typed views instead of ViewData and weakly typed helpers as they lack Intellisense and are source of many errors and ugly views.

Model:

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; }
}

Controller:

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);
}

Strongly typed view:

<%@ 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) %>

Now all that's left is replace the hardcoded values with ones coming from your database, by mapping the returned resultset from the repository into IEnumerable<SelectListItem>.

完美的未来在梦里 2024-11-22 08:51:05

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

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;
}

我同意达林的观点,你应该使用视图模型而不是视图数据。就我而言,我将上述方法放入视图模型中,并在我看来调用该方法。

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

This gives you two different ways to add items to a list of SelectListItems. You can bind with an existing collection or you can populate it manually.

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;
}

I agree with Darin that you should be using view models instead of viewdata. In my case, I put the above method into a view model and in my view I call that method.

<%: Html.DropDownListFor(m => m.SomeProperty, Model.GetSomeSelectList()) %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文