I’m having issues with razor, I’m trying to access the first element of a list. But when I try to cast an element with item2.hijos[0].ruta, I get an error.
But when I use item2.hijos.count(), it returns 1. So there is an element but somehow razor doesn’t want me to access it.
Here is my code. items2.hijos.first() doesn’t work either.
foreach (var item in Model)
{
<li id="@(item.CNombreManual)" onclick="mostrarEsconderHijos(this.id)" class="list-group-item-heading">@(item.CNombreManual)</li>
foreach (var item2 in item.hijos)
{
<li id="<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="efb0af">[email protected]</a>(item.cNombreManual)" class="list-group-item" style="tex-align:left; display:none">
@(item2.CNombreManual)
@Html.ImageActionLink("Ver PDF", "Descargar", "Manual", new { NombreArchivo = item2.hijos[0].Ruta }, null, "~/imgs/LecturaPdf.png")
</li>
}
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Just check whether you have the items in the array item2.hijos[] before using the array. It could be printing the values for the first few records and then throwing an error where there is no element. So it can be happening for any hijos array of item2 of item. Just ensure you check for the array size before using it.
item2.hijos[0].Ruta // replace this with the following item2.hijos.Length > 0? item2.hijos[0].Ruta : 0
I think you can even do shorter. item2.hijos[0]?.Ruta ?? 0
Method 2
I don’t know the details of your model, but the problem is that you’re iterating (foreach) of item’s hijos, but then accessing of item2‘s hojos.
I think you want to access item2.Ruta:
foreach (var item2 in item.hijos)
{
(...) item2.Ruta // not item2.hijos[0].Ruta
If you actually need to access item2.hijos[0].Ruta then you need check if it exists first.
You can do that using:
You could also use item2.hijos.FirstOrDefault()?.Ruta (see Enumerable.FirstOrDefault Method).
Btw. the whole hijos could also be null, so it may be necessary to check if the whole collection (item2.hijos).
Finally, you may want to add another foreach for item2.hijas rather than access element 0.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0