Waqas Nawaz Warraich
Waqas Nawaz Warraich

Reputation: 441

Why does rendering data with viewbag causes an error?

why this error occur with .net mvc razor view

enter image description here

Controller Code

ViewBag.LowStock = db.StockInformations.Where(x => x.Qty <= x.MinStockLevel);

View Code

  @{
List<StockInformation> DangerLavel = (List<StockInformation>)ViewBag.LowStock;
var count = 0;
ViewBag.Title = "Create";
}

Upvotes: 2

Views: 52

Answers (2)

Caique C Pereira
Caique C Pereira

Reputation: 121

The error occurs because you are storing a DbQuery<StockInformation> and trying to get a List<StockInformation>.

The code below returns a DbQuery<StockInformation>.

db.StockInformations.Where(x => x.Qty <= x.MinStockLevel)

To fix it just call the ToList method:

db.StockInformations.Where(x => x.Qty <= x.MinStockLevel).ToList();

The ToList method will create a List based on the DbQuery returned from the Where method.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726799

Since LowStock is a query, you cannot cast it to List<StockInformation>. Instead, you should call ToList() to it:

List<StockInformation> DangerLavel = ViewBag.LowStock.ToList();

The call retrieves the data from DbQuery after applying the filter, producing a list in memory.

Upvotes: 3

Related Questions