Skip to main content
 首页 » 编程设计

c#之如何将 IEnumerableSelectListItem> 集合传递给 MVC 局部 View ,每个请求仅进行一次数据库查找

2024年02月13日31小虾米

假设给定一个 html 表格的分部 View ,每个表格行都存在一个嵌套的分部 View ,如下所示:

外部局部 View

<table> 
<thead> 
  <tr> 
    <th>Item Name</th> 
    <th>Cost</th> 
    <th>Category</th> 
  </tr> 
</thead> 
<tbody> 
@for (int i = 0; i < Model.PurchaseItems.Count; i++) 
{  
  @Html.Partial("_PurchaseItemsDetail", Model.PurchaseItems[i]) 
}      
</tbody> 
</table> 

内部局部 View ,注意:外部 View 可以在单个请求中多次使用此局部 View ,但是如果使用 AJAX 请求,它也可以只使用一次

<tr id="@Model.ID"> 
  <td>@Html.TextBoxFor(x => x.ItemName)</td> 
  <td>@Html.TextBoxFor(x => x.Cost)</td> 
  <td> 
    @Html.DropDownListFor(x => x.Category, CATEGORY_COLLECTION) 
  </td> 
</tr> 

问题:给定这个旨在灵活的内部 View ,查询数据库和临时存储 IEnumerable<SelectListItem> 的最佳方式是什么?与下拉列表一起使用的集合?我能想到的方法:

方法一:这似乎是最简单的,但感觉违反了MVC原则。在内部局部 View 中计算并以仅命中一次数据库的方式存储在 ViewData 集合中:

    @{ 
     if (ViewData["Categories"] == null) 
     { 
       ViewData["Categories"] = API.GetCategories(); 
     } 
    } 

然后在后面的 View 中

  <td> 
    @Html.DropDownListFor(x => x.Category, ViewData["Categories"]) 
  </td> 

这很好,因为 View 会自行决定如何填充其包含的下拉列表。它不依赖于 View 模型。

方法 2:同上,除了在返回内部局部 View 的各种 Controller 方法中设置 ViewData。这种方式似乎更符合 MVC 最佳实践,但考虑到每个 Controller 方法都需要正确设置 ViewData 以及创建必要的 View 模型,因此维护起来似乎更加乏味和困惑。

方法 3:这看起来最费功夫,最难维护,但最符合 MVC 原则。避免完全使用 ViewData,而是将对集合的引用与分部 View 模型中的其他属性一起存储。 Controller 负责创建集合,然后在每个表行的 View 模型中存储一个引用。

public class PurchaseItemModel 
{ 
  public string ItemName { get; set; } 
  public decimal Cost { get; set; } 
  public string Category { get; set; } 
 
  // add this 
  public IEnumberable<SelectListItem> Categories { get; set; } 
} 

并且在为内部 View 提供服务的每个 Controller 中

// if dealing with multiple rows (GET) 
IEnumerable<SelectListItem> collection = API.GetPurchaseItemList(); 
foreach (PurchaseItemModel pim in OuterModel.PurchaseItemModels) 
{ 
  pim.Categories = collection; 
} 

或

// if dealing with a single row (Ajax) 
purchaseItem.Categories = API.GetPurchaseItemList(); 

然后在后面的 View 中

  <td> 
    @Html.DropDownListFor(x => x.Category, x.Categories) 
  </td> 

也许这只是主观问题,但似乎有针对此类情况的最佳实践。有什么想法吗?

请您参考如下方法:

继续创建一个 ViewModel 类,例如

public class PurchaseItemViewModel 
{ 
  public string ItemName { get; set; } 
  public decimal Cost { get; set; } 
  public string Category { get; set; } 
  public IEnumberable<Category> Categories { get; set; } 
 
  public PurchaseItemViewModel(PurchaseItemModel item, List<Category> categories) 
  { 
       //initialize item and categories 
  } 
} 

在 Controller 中获取所有项目,然后获取所有类别,然后将购买项目设置到 ViewModel 并设置类别。因此,您会将 ViewModel 类传递给 View 。