Search code examples
asp.netasp.net-mvcasp.net-mvc-4razor-2

is it possible to get ViewData collection length


Because i have to introduce some conditional if else statement in entire code base on collection index number

controller passing :

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

view :

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

            }

compile time error :

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


Solution

  • You can Cast it to IList and use Count:

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