Hi,
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: 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.
Thank You in advance :)