I am currently creating an e-commerce site using C# ASP.NET MVC and have just come across a problem. On pages such as product pages and search results pages, I have to pass Lists of data from my controller to the ViewPage and that works just fine. However, a null reference exception occurs if the Viewdata equals null. It happens inside the viewpage when it loops through the ViewData and displays products or reviews.
//ProductController.cs
public ActionResult Products_Sub(string category, int page) { ViewData['Products'] = database.GetByCategory(category, page); return View(); }
//ViewPage.cs — product loop
<ul> foreach (E_Store.Models.Product product in ViewData['Products'] as List<e_store.models.product>) {%> <li> <img alt='<%= product.Title%>' src='<%= product.Thumbnail %>' /> <a href='/<%=product.Category %>/<%= product.SubCategory %>/<%= product.ASIN %>/1'> <%=product.Title%></a> </li> }%> </ul>
The Null Reference Exception occurs when the following piece of code is reached:
<ul> foreach (E_Store.Models.Product product in ViewData['Products'] as
What I would like to know is the best way to catch this type of error if it does happen, without resorting to if statements that check to see if it is null.
If anyone knows of a good way of doing this I would really love to know.
In your case I would have your database.GetByCategory(category, page) method simply return an empty list rather than null, this way your foreach statement just won’t have any data to loop through but you won’t get a null exception.
In the case that you’re not dealing with a list and the item is null, we use
To get the item’s HTML value, it will return ” if the item is null.