【发布时间】: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;
}
}
所以两个主要问题是:
如何填写模型页面的列表?
如何将模型页面上的列表连接到视图中的下拉列表?
提前致谢!
【问题讨论】:
-
如果您正在寻找对您的代码的审查,并且您没有特定的问题(即不一定有问题),有一个专门针对它的 StackExchange 站点:codereview.stackexchange.com
标签: c# asp.net-mvc visual-studio nopcommerce