Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I get around this exception?
C#
@foreach (var genre in Model)
{
     @Html.ActionLink(genre.Name,"Browse",new {genre=genre.Name})
}
Posted
v2
Comments
earloc 20-Dec-12 4:59am    
what line is causing the Exception? could only be trying to get the enumerator for "Model" or accessing the "Name"-Property of a null reference in "genre"

1 solution

If you have supplied the lines of code that are throwing, and Name is a string, then genre is null.


You make sure genre is not null. The most likely solution to you problem is to skip the link creation there are a few ways to do this, but I'm not sure which'll work in Razor. this should be safe:

C#
@foreach (var genre in Model)
{
     if(genre != null)
     {
         @Html.ActionLink(genre.Name,"Browse",new {genre=genre.Name})
     }
}


if you want to be really belt & braces and avoid any empty links

SQL
@foreach (var genre in Model)
{
     if(genre != null && !string.IsNullOrWhiteSpace(genre.Name))
     {
         @Html.ActionLink(genre.Name,"Browse",new {genre=genre.Name})
     }
}



Of course, the last example is only good if Name is a string.

The other thing you should check is the code that fills Model, the chance are there shouldn't be any nulls in there.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900