foreach循环抛出ArgumentOutOfRangeException

时间:2018-04-08 20:13:54

标签: c# razor

我正在编写一个APS.NET MVC 5应用程序。我陷入了一个小问题,我实际上无法搞清楚。

我收到如下错误:

  

System.ArgumentOutOfRangeException:'索引超出范围。必须是非负数且小于集合的大小。参数名称:   索引'

我从db获取数据并传递给具有不同数据集的视图。

    List<MasterEntity> ListOfmasterEntity = new List<MasterEntity>();
    ListOfmasterEntity.Add(masterEntityA);
    ListOfmasterEntity.Add(masterEntityB);

    return View(ListOfmasterEntity)

我已经像下面那样实例化了我的主人。 MasterEntity是包含List的超类,其中T是各种实体

public class PageEntity
{
        public PageEntity()
        {

        }

        public string DesignId { get; set; }
        public string DesignName { get; set; }
        public string DesignStatus { get; set; }
}

大师班

public MasterEntity()
{
    this.ListOfPageEntity = new List<PageEntity>();
    this.ListOfuserEntity = new List<UserEntity>();
}


public List<UserEntity> ListOfuserEntity { get; set; }
public List<PageEntity> ListOfPageEntity { get; set; }

在我执行LINQ的视图页面上,我的代码断开如下。

@foreach (var item in Model.First().ListOfPageEntity)
{
   //This brings data for n times then 1 more lookup in collection is breaking the code. I don't exactly know why!
}

1 个答案:

答案 0 :(得分:0)

行。所以最后我在调试后花了几个小时得到了答案。就像在编码时发生一样,它变得愚蠢。

简答:我在cshtml上处理null,然后将其转换为数组。

说明: 从我的控制器我传递MasterObject来查看。 MasterObject是各种其他集合对象的蓝图。 MasterObject中有一些动态值。在渲染剃刀视图的同时,我调用了属性来渲染它,但实际上它从未被初始化,因为没有返回它的表。所以,我需要明确处理null。最后,完成了它。

相关问题