I have a page containing a Chart object that I use as the default route in ASP.NET MVC. When I run the app, I get an exception due to a null reference. If I use a URL with the controller and action given explicitly, everything works fine.
Here is the code to show what I mean…
In RegisterRoutes:
routes.MapRoute("Default", "{controller}/{action}", new { controller = "Dashboard", action = "Index" });
DashboardModel.cs:
public class DashboardModel
{
public Chart MyChart { get; set; }
}
DashboardController.cs
public ActionResult Index()
{
Chart chart = CreateChart();
DashboardModel dm = new DashboardModel();
dm.MyChart = chart;
return View(dm);
}
Index.aspx
<% chartPanel.Controls.Add(Model.MyChart); %>
<asp:Panel ID="chartPanel" runat="server"></asp:Panel>
Launching the app from the debugger with the URL http://localhost:2313/ results in NullReferenceExcpetion on the first line given above in Index.aspx. If I put http://localhost:2313/Dashboard/Index in the browser, the chart is displayed correctly. I set a breakpoint in the Index() action, and it creates a valid model and chart, and the breakpoint is only hit once before the exception occurs.
Why is the model null? It should be created every time that my action method is called from what I’ve seen. There must be something more going on with the default routing that I am not understanding.
It appears that I was mistaken about the Model being null. Smashd’s question got me thinking more about the URL, and that was the cause of the exception. Although I don’t understand why the Chart needs a URL to display properly, I was able to add a workaround for the problem.
I changed the default routing parameters as follows:
Then I added a new action method to my controller that forces a redirect:
This gets me to the Index with a fully formed URL. There might be a better solution for this, but at least the redirect works transparently.