是否有可能获得 ViewData 集合长度

is it possible to get ViewData collection length

因为我必须在整个代码库中根据集合索引号

引入一些条件 if else 语句

控制器传递:

 ViewData["productSl_1"] = appDataContext.Products.ToList();

查看:

@{var viewDataProd = ViewData["productSl_1"] as IEnumerable<Nazmulkp.Models.Product>;}
    @for (var i = 0; i < viewDataProd.length; i++) {
            {

            }

编译时错误:

does not contain a definition for 'length' and no extension method 'length' accepting a first argument of type 'length'

您可以将其转换为 IList 并使用计数:

ViewData["productSl_1"] = appDataContext.Products.ToList();
@{ var viewDataProd = ViewData["productSl_1"] as IList<Nazmulkp.Models.Product>;}
    @for (var i = 0; i < viewDataProd.Count; i++) {
    {

    }

我不会使用视图数据。我会将整个列表按原样传递给视图。

您的操作方法看起来像这样。从您的数据源获取产品并将此列表直接发送到视图:

// Make use of the using directive
using Nazmulkp.Models;

public ActionResult Index()
{
     // Get you products from your data source
     // I used a repository, but you can use any other way to get your data
     List<Product> products = productRepository.GetAll();

     return View(products);
}

设置您的视图以接收产品列表。使用 for loop 而不是 foreach loop 循环遍历这些产品。您现在可以访问一个索引,即 i,然后您可以使用该索引访问列表中的单个产品,例如:

@Model[i].Name
@Model[i].Description
@Model[i].Price

您的视图可能如下所示:

@model List<Nazmulkp.Models.Product>

@for (i = 0; i < Model.Count; i++)
{
     <div>@Model[i].Name</div>
}

如果您需要在 for loop 中使用 if else statement,那么它将看起来像这样:

@model List<Nazmulkp.Models.Product>

@for (i = 0; i < Model.Count; i++)
{
     if (i == 1)
     {
         <div>@Model[i].Name</div>
     }
     else
     {
         <div>Do something else</div>
     }
}