I am trying to output a player's stats in a table. Not all players will have stats depending on the day. I have tried other ways and all are still complaining. Here is the code I have now:
<tbody>
@foreach(var player in @ViewBag.Roster){
int index = 0;
<tr>
<td>@player.Name, @player.TeamName @player.Position</td>
if(@ViewBag.Stats[index] == null){
<td>--</td>
<td>--</td>
<td>--</td>
<td>--</td>
}
else{
<td>@ViewBag.Stats[index].Points</td>
<td>@ViewBag.Stats[index].Rebounds</td>
<td>@ViewBag.Stats[index].Assists</td>
<td>@ViewBag.Stats[index].Turnovers</td>
}
</tr>
index++;
}
</tbody>
Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference
Source Error:
Line 32: }
Line 33: else{
Line 34: @ViewBag.Stats[index].Points
Line 35: @ViewBag.Stats[index].Rebounds
Line 36: @ViewBag.Stats[index].Assists
OK I am posting the full answer here -
Try @
before if(@ViewBag.Stats[index] == null){
and remove @
from @ViewBag
inside the if
so that it look like this - @if(ViewBag.Stats[index] == null){
You are setting index = 0
, inside foreach
, so it is initialised in every loop. Initialise it outside foreach
like this
var index = 0;
foreach ...
if you are facing problem for the scope try this -
@{
var index = 0;
foreach (....) {
.......
index++
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With