Reputation: 57
im passing list data in the viewbag from the controller . while accessing the viewbag as list getting error.
error - 'Object reference not set to an instance of an object.'
getting error at this line. ViewBag.Total_PowerList as IEnumerable<TransformerEnergyMonitoring.Models.KWHConsumption>
view
@model IEnumerable<TransformerEnergyMonitoring.Models.KWHConsumption>
<div class="row">
<div class="table-responsive">
<table id="myTable" class="table table-bordered table-hover table-striped">
<thead class="table-header">
<tr>
<th>Date</th>
<th>KWH Reading</th>
<th>KWH Consumption</th>
</tr>
</thead>
<tbody>
@foreach (var item in (ViewBag.Total_PowerList as IEnumerable<TransformerEnergyMonitoring.Models.KWHConsumption>))
{
<tr>
<td>@item.timeStamp</td>
</tr>
}
</tbody>
</table>
</div>
</div>
dataset
{ timeStamp = 12/5/2020 12:00:00 AM, finalState = 47326.95, consuption = 1455.71 }
Controller
public ActionResult KWHDateWise(RangeSelection RS)
{
DateTime ToDate = Convert.ToDateTime(RS.ToDate).AddDays(1);
RS.ToDate = ToDate;
List<KWHConsumption> kwhcon = new List<KWHConsumption>();
var Total_PowerList = db.Total_Power.Where(u => u.DeviceImei == RS.DeviceImei && (u.DeviceTimeStamp >= RS.FromDate && u.DeviceTimeStamp <= RS.ToDate)).OrderByDescending(u => u.DeviceTimeStamp).ToList();
ViewBag.Total_PowerList= Total_PowerList
.GroupBy(
i => i.DeviceTimeStamp.Date,
(timeStamp, dayilyData) => new { timeStamp, dayilyData })
.Select(i => new
{
i.timeStamp,
finalState = i.dayilyData.Max(x => x.KWH),
consuption = (i.dayilyData.Max(x => x.KWH) - i.dayilyData.Min(x => x.KWH))
})
.ToList();
return PartialView("~/Views/TransEnergyHistory/_KWH.cshtml", kwhcon);
}
Model
public class KWHConsumption
{
public DateTime timeStamp { get; set; }
public double finalState { get; set; }
public double consuption { get; set; }
}
Upvotes: 0
Views: 2606
Reputation: 1193
Whenever you are using a viewbag is a dynamic structure that doesnt care about the datatype is having inside, what you sohuld be doing is casting your datatype to your desired type here an example:
Provided this TestModel
public class TestModel
{
public string Id { get; set; }
public int Number { get; set; }
public string Name { get; set; }
}
and this Action in the controller
public IActionResult Index()
{
var vm = new List<TestModel>() {
new TestModel(){
Id = "randomId1",
Name = "randomName1",
Number = 2
},
new TestModel(){
Id = "randomId2",
Name = "randomName2",
Number = 1
},
new TestModel(){
Id = "randomId3",
Name = "randomName3",
Number = 3
},
};
ViewBag.TestModels = vm;
return View();
}
In your view it should look like this
@foreach (var item in (ViewBag.TestModels as IEnumerable<TestModel>))
{
<tr>
<td>@item.Id</td>
<td>@item.Number</td>
<td>@item.Name</td>
</tr>
}
Im assuming in your case the way you want to cast it is
(ViewBag.Total_PowerList as IEnumerable<TransformerEnergyMonitoring.Models.Total_Power>)
Upvotes: 1