Tuesday, September 11, 2012

NullReferenceException in Html.ValidationSummary()

I was implementing a view using ASP.NET MVC, MVC 4 in this case but I suspect the version is irrelevant. I received a NullReferenceException when any validation failed, ie the model state was invalid.

The stack trace was close to useless and looked similar to the following:

at ASP._Page_Views_Issue_Create_cshtml.Execute() in c:\projects\au\AgileTraxx\Web\Views\Issue\Create.cshtml:line 26
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.RunPage()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)

Line 26 which the stack trace referring to was:

Html.ValidationSummary();

This wasn’t much help either. It took me a lot of experimentation to find out that in this particular case the property Model of the view was null. Once I set the model for this view, it all went nicely.

Note that not always it is obvious from scanning the code that one didn’t set the model for a view. Therefore I’m blogging my experience here and to give the recommendation that should you encounter the same or similar behavior, to the following:

  1. Set a breakpoint on the line where the exception is thrown.
  2. Debug the application
  3. When the breakpoint is hit, enter “Model” in the “Immediate Window” in Visual Studio and check whether it outputs “null”.

Happy coding!

1 comments:

Anonymous said...

Thanks You!!!

Post a Comment

All comments, questions and other feedback is much appreciated. Thank you!