【问题标题】:Best Practice for adding List<string> to DropDownList将 List<string> 添加到 DropDownList 的最佳实践
【发布时间】:2023-04-01 04:09:01
【问题描述】:

我的控制器如下所示:

var _engine = new NopEngine();
            var categoryService = _engine.Resolve<ICategoryService>();
            var allCategory = categoryService.GetAllCategories();

            List<string> ConvertedList = new List<string>();

            for (int i = 0; i < allCategory.Count; i++)
            {
                ConvertedList.Add(allCategory[i].Name);
            }

            //fill the viewbag
            ViewBag.CategoryList = ConvertedList;

            return View("Nop.Plugin.Misc.ExportAttributes.Views.MiscExportAttributes.ExportCalculationSheet");

所以基本上我用一个字符串列表填充 ViewBag。

我的看法如下:

@{
    Layout = "";
}
@using Telerik.Web.Mvc.UI;
@model ExportCalculationSheetModel
@using Nop.Plugin.Misc.ExportAttributes.Models;
@using Nop.Web.Framework;
@using Nop.Core.Domain.Catalog;
@using (Html.BeginForm())
{
    <table class="adminContent">
        <tr>
            <td colspan="2">
                <b>Filter op Categorie:</b>
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.searchCategory):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(x => x.searchCategory, new SelectList(ViewBag.CategoryList, "Name"))
            </td>
        </tr>
</table>

这可行,DropDownList 会填充正确的值。但我不认为 ViewBag 是“最佳实践”,我听说过使用模型从中选择列表,我已经在视图中添加了对模型的引用:

@model ExportCalculationSheetModel

如何在模型类中填写列表并在我的视图中使用它?

我已经尝试通过以下方式填充模型类,但没有成功:

public List<string> AllCategories
        {
            get
            {
                return AllCategories;
            }
            set
            {
                var _engine = new NopEngine();
                var categoryService = _engine.Resolve<ICategoryService>();
                var allCategory = categoryService.GetAllCategories();

                List<string> ConvertedList = new List<string>();

                for (int i = 0; i < allCategory.Count; i++)
                {
                    ConvertedList.Add(allCategory[i].Name);
                }
                AllCategories = ConvertedList;
            }
        }

所以两个主要问题是:

  1. 如何填写模型页面的列表?

  2. 如何将模型页面上的列表连接到视图中的下拉列表?

提前致谢!

【问题讨论】:

标签: c# asp.net-mvc visual-studio nopcommerce


【解决方案1】:

DropDownListFor 唯一需要的是IEnumerable&lt;SelectListItem&gt;(即,它可以是列表/集合/可查询/等等)。现在的问题是你只是有一个列表string 而不是SelectListItem。使用一点 LINQ-fu 很容易解决这个问题:

@Html.DropDownListFor(x => x.searchCategory, Model.AllCategories.Select(m => new SelectListItem { Value = m, Text = m }))

但是,更好的方法是让AllCategories 立即返回一个SelectListItems 列表(假设它仅用于填充下拉列表)。

private IEnumerable<SelectListItem> allCategories;
public IEnumerable<SelectListItem> AllCategories
{
    get
    {
        if (allCategories == null)
        {
            var _engine = new NopEngine();
            var categoryService = _engine.Resolve<ICategoryService>();

            allCategories = categoryService.GetAllCategories().Select(m =>
                new SelectListItem { Value = m.Name, Text = m.Name });
        }

        return allCategories;
    }

    // You don't need a setter
}

第一次访问AllCategories 时,关联的私有变量allCategories 将为空,因此您的服务启动并获取类别列表。 Select 用于将返回的类别转换为SelectListItems 的集合。如果您的类别有类似Id 的属性,您应该将其用于Value 而不是Name。对AllCategories 的任何后续访问都将简单地返回存储在私有中的值,而不会再次访问数据库。

奖金专业提示

如果您确实需要为此使用 for 循环,则无需创建新列表、将项目添加到循环中的列表中,然后返回该列表。使用yield 更容易。例如:

public IEnumerable<int> Numbers
{
    for (int i = 0; i < 10; i++)
    {
        yield return i;
    }
}

【讨论】:

  • 谢谢!有效!感谢您的提示,我一定会使用它:)
【解决方案2】:

改变

List<string> ConvertedList = new List<string>();

List<SelectList> ConvertedList = new List<SelectList>();

不需要循环。可以直接将数据库返回列表值添加到ConvertedList

看看这个样本 Binding Data To DropDownList MVC Razor

这是一个很好的sample

【讨论】:

  • 我使用 for 循环从 List 中过滤掉 Name 值,这是一个接口,所以我将有一个字符串列表,我应该将该列表转换为 ?
【解决方案3】:

也许你可以试试这个:

从模型中的字典开始

    public class YourOptions
    {
        public Dictionary<int, string> Option { get; set; }

        public YourOptions()
        {
            Option = new Dictionary<int, string>()
            {
                //Here you should put your code, this is an example
                { 0, "Option 1"},
                { 1, "Option 2"},
                { 2, "Option 3"},
                { 3, "Option 4"},
                { 4, "Option 5"},
                //Here you should put your code, this is an example
            };

    }

在视图中

@Html.DropDownListFor(model => model.Option.Keys,
                         new SelectList(
                             Model.Option, 
                             "Key", 
                             "Value"))

对不起我的英语不好!希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多