在 ASP.NET MVC 中,如何将多个选择列表绑定到 IList收藏?

发布于 2024-10-10 07:26:46 字数 860 浏览 1 评论 0原文

我有一个带有 List 属性的模型。我想呈现几个绑定到该属性的选择列表。

例如,假设我的模型名为“Favories”,我让用户选择几种最喜欢的颜色。

public class Favorites
{
    public List<string> FavoriteColors { get; set;}
}

我尝试使用索引绑定到集合,但遇到了问题,很可能是因为FavoriteColors 为空。这是不起作用的代码(空异常):

@Html.DropDownListFor(m => m.FavoriteColors[0], ColorSelectList, "Select a color (required)")
@Html.DropDownListFor(m => m.FavoriteColors[1], ColorSelectList, "Select a color (optional)")
@Html.DropDownListFor(m => m.FavoriteColors[2], ColorSelectList, "Select a color (optional)")

我意识到我可以通过几种方式解决这个问题。

  1. 使用 3 个空值填充 favoriteColors。但这感觉不对,因为我的模型将包含无效数据(空值),我必须在代码中的许多其他位置解决该问题。
  2. 更改我的模型,使我拥有 3 个字符串属性(例如,FavoriteColor1、FavoriteColor2、FavoriteColor3)。绑定会更容易,但我仍然需要使用一堆代码来解决该设计。

有更好的办法吗?

I have a model with a List<string> property. I want to present several select lists that bind to that property.

For example, supposed my model is named Favories, and I let the user select several favorite colors.

public class Favorites
{
    public List<string> FavoriteColors { get; set;}
}

I tried binding using the indexes to the collection, but I ran into problems, most likely because FavoriteColors was empty. Here's the code that doesn't work (null exception):

@Html.DropDownListFor(m => m.FavoriteColors[0], ColorSelectList, "Select a color (required)")
@Html.DropDownListFor(m => m.FavoriteColors[1], ColorSelectList, "Select a color (optional)")
@Html.DropDownListFor(m => m.FavoriteColors[2], ColorSelectList, "Select a color (optional)")

I realize I could fix this a couple ways.

  1. Populate FavoriteColors with 3 empty values. But this doesn't feel right since my model would have invalid data (empty values) that I'd have to workaround in a bunch of other places in my code.
  2. Change my model so that I have 3 string properties (e.g. FavoriteColor1, FavoriteColor2, FavoriteColor3). Binding would be easier, but I'd still have to work around that deisgn with a bunch of code.

Is there a better way?

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

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

发布评论

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

评论(2

抱猫软卧 2024-10-17 07:26:46

这是一个简单的解决方案,适用于使用 Razor 和标准 DropDownListFor 帮助程序的您。

所有内容均基于示例数据和文件,您可以更改这些数据和文件以满足您的需求:

HomeController.cs

public class HomeController : Controller
    {
        public class FavoriteColorModel
        {
            public List<string> FavoriteColors { get; set; }
        }

        public ActionResult Index()
        {
            ViewBag.ColorList = new[]
                                    {
                                        "Blue",
                                        "Red",
                                        "Green",
                                        "Orange"
                                    };
            var favoriteColors = new FavoriteColorModel()
                                     {
                                         FavoriteColors = new List<string>()
                                                              {
                                                                  "Color1",
                                                                  "Color2",
                                                                  "Color3"
                                                              }
                                     };
            return View(favoriteColors);
        }

        [HttpPost]
        public ActionResult Save(FavoriteColorModel model)
        {
            TempData["SelectedColors"] = model.FavoriteColors;
            return RedirectToAction("Index");
        }
    }

Index.cshtml

@model MvcApplication4.Controllers.HomeController.FavoriteColorModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

@if (TempData["SelectedColors"] != null)
{
    <text>
    You have selected the following colors:<br />
    <ul>
    @foreach (var color in TempData["SelectedColors"] as List<string>)
    {
        <li style="color:@color">@color</li>
    }
    </ul>
    </text>
}

@using (Html.BeginForm("Save", "Home"))
{
    @: Favorite colors:
    for (var index = 0; index < Model.FavoriteColors.Count; index++)
    {
        @Html.DropDownListFor(model => model.FavoriteColors[index], new SelectList(ViewBag.ColorList))
    }
    <br />
    <input type="submit" value="Save" />
}

您选择的颜色将在提交后显示在列表元素中。您可以通过向 Color1Color2 数组等添加项目来控制要保存的颜色数量

Here is a simple solution that will work for you using Razor and standard DropDownListFor<T> helpers.

All based on example data and files which you can change to suit your needs:

HomeController.cs

public class HomeController : Controller
    {
        public class FavoriteColorModel
        {
            public List<string> FavoriteColors { get; set; }
        }

        public ActionResult Index()
        {
            ViewBag.ColorList = new[]
                                    {
                                        "Blue",
                                        "Red",
                                        "Green",
                                        "Orange"
                                    };
            var favoriteColors = new FavoriteColorModel()
                                     {
                                         FavoriteColors = new List<string>()
                                                              {
                                                                  "Color1",
                                                                  "Color2",
                                                                  "Color3"
                                                              }
                                     };
            return View(favoriteColors);
        }

        [HttpPost]
        public ActionResult Save(FavoriteColorModel model)
        {
            TempData["SelectedColors"] = model.FavoriteColors;
            return RedirectToAction("Index");
        }
    }

Index.cshtml

@model MvcApplication4.Controllers.HomeController.FavoriteColorModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

@if (TempData["SelectedColors"] != null)
{
    <text>
    You have selected the following colors:<br />
    <ul>
    @foreach (var color in TempData["SelectedColors"] as List<string>)
    {
        <li style="color:@color">@color</li>
    }
    </ul>
    </text>
}

@using (Html.BeginForm("Save", "Home"))
{
    @: Favorite colors:
    for (var index = 0; index < Model.FavoriteColors.Count; index++)
    {
        @Html.DropDownListFor(model => model.FavoriteColors[index], new SelectList(ViewBag.ColorList))
    }
    <br />
    <input type="submit" value="Save" />
}

Your selected colors will appear in a list element upon submit. You can control the amount of colors you wish to save by adding items to the Color1, Color2 array etc.

Peace.

后知后觉 2024-10-17 07:26:46

我就是这样做的,因为我不喜欢 MVC 处理下拉列表的方式。

   foreach (var ColorArray in m.FavoriteColors)
{ %>

 <select name='colors'>
 <% foreach (var color in ColorArray) 
{%>

  <option><%= color.ToString() %></option>

<% { %>
 </select>
}%>

您可以将其硬编码为您想要的索引,但您会得到总体思路。此外,这还允许您在任何您想要有选择地处理这些情况的地方进行空检查。

This is how I would do it because I dont like the way MVC handles drop down lists.

   foreach (var ColorArray in m.FavoriteColors)
{ %>

 <select name='colors'>
 <% foreach (var color in ColorArray) 
{%>

  <option><%= color.ToString() %></option>

<% { %>
 </select>
}%>

You could hard code it to just the indexes you want but you get the general idea. Also this would allow you to put in null checks whereever you like to handle those cases selectively.

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