Elliott
Elliott

Reputation: 2205

ASP.NET MVC NullReferenceException when returning view

This was working and just up and quit one day when I sat down to work on it. I can't for the life of me figure it out. The error I'm getting is:

enter image description here

I can launch the application but as soon as I navigate to this page it kicks up the error while trying to display the view.

Here's my controller

 // GET: Form/Create
    public ActionResult Create()
    {
        List<METHOD> methods = new List<METHOD>();
        List<NATION> nations = new List<NATION>();
        List<LANGUAGE> languages = new List<LANGUAGE>();
        List<string> headers = new List<string>();
        List<string> footers = new List<string>();
        List<string> cssFiles = new List<string>();

        using(var context = new Entities(_connectionString))
        {

            // Get a list of methods to choose from incase they want to change the method
            methods = context.METHODs.ToList();

            // Get list of nations to choose from
            nations = context.NATIONs.OrderBy(x => x.NAME).ToList();

            // Get list of languages 
            languages = context.LANGUAGES.OrderBy(x => x.DESCRIPTION).ToList();

            // Get list of headers that are used today (from the DB...not solution)
            headers = context.WEB_CONTACT_DETAILs.Select(x => x.HDR_LINK).Distinct().ToList();
            headers.Sort();
            // Get list of footers that are used today (from the DB...not solution)
            footers = context.WEB_CONTACT_DETAILs.Select(x => x.FTR_LINK).Distinct().ToList();
            footers.Sort();
            // Get list of headers that are used today (from the DB...not solution)
            cssFiles = context.WEB_CONTACT_DETAILs.Select(x => x.CSS_LINK).Distinct().ToList();
            cssFiles.Sort();
        }
        ViewData["methods"] = methods;
        ViewData["nations"] = nations;
        ViewData["languages"] = languages;
        ViewData["headers"] = headers;
        ViewData["footers"] = footers;
        ViewData["cssFiles"] = cssFiles;

        return View();
    }

I've stepped through everything and all the data loads correctly from the DbContext and the list objets are exactly how I would expect right before I return the view.

Here's the view

@using Company.ContactFormAdmin.Web;
@using Company.ContactFormAdmin.Web.Models
@model FormViewModel
@{
    ViewBag.Title = "Edit";
    List<METHOD> methods = (List<METHOD>)ViewData["methods"];
    List<NATION> nations = (List<NATION>)ViewData["nations"];
    List<LANGUAGE> languages = (List<LANGUAGE>)ViewData["languages"];
    List<string> headers = (List<string>)ViewData["headers"];
    List<string> footers = (List<string>)ViewData["footers"];
    List<string> cssFiles = (List<string>)ViewData["cssFiles"]; //<--this is     where the exception is getting thrown.
}


<h2>New Contact Form</h2>
<div class="container"> //Truncated to keep it short...

I've stepped through each of the List objects above and each populates with the data I'm passing from the controller. I've also tried setting them all to null and the error still gets thrown in the same place. I also tried not passing anything back from the controller and it still happens.

@{
    ViewBag.Title = "Edit";
    List<METHOD> methods = null;// (List<METHOD>)ViewData["methods"];
    List<NATION> nations = null;// (List<NATION>)ViewData["nations"];
    List<LANGUAGE> languages = null;// (List<LANGUAGE>)ViewData["languages"];
    List<string> headers = null;// (List<string>)ViewData["headers"];
    List<string> footers = null;// (List<string>)ViewData["footers"];
    List<string> cssFiles = null;// (List<string>)ViewData["cssFiles"];
}

I've also tried cleaning and rebuilding to no avail. If I remove the last line ("cssFiles") the error is thrown on the preceding line ("footers").

Full Stack Trace

   at ASP._Page_Views_Form_Create_cshtml.Execute() in c:\Projects\ConsumerServices\ContactFormAdmin\ContactFormAdmin_Soln-MVC-EB\ContactFormAdmin.Web\Views\Form\Create.cshtml:line 8
   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.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)

Anyone know how I can troubleshoot this further or have dealt with this before?

Upvotes: 2

Views: 1812

Answers (2)

esenkaya
esenkaya

Reputation: 398

Looks like you have already made it work. FYI: ViewData object must be available in order to use it in View. If it is null it will throw an error. Before you use it in view check if it is not null then use it as below.

NOT Works!

 <div>ViewData["cssFiles"]</div>

Works!

@if (ViewData["cssFiles"] != null)
{
    <div>ViewData["cssFiles"]</div>
}

Upvotes: 1

Elliott
Elliott

Reputation: 2205

By process of elimination I was able to resolve this. I don't know why it all of a sudden became an issue but the error was in fact in a different part of the view, lower down.

I was using traditional Html <input> tags and not ASP.NET's Html helper. By replacing this:

<input class="form-control" id="WEB_PAGE_NAME" name="WEB_PAGE_NAME" value="@Model.WEB_PAGE_NAME">

with this:

@Html.TextBoxFor(model => model.WEB_PAGE_NAME, new { @class = "form-control" })

I was able to get the error to go away. I do not know why the traditional tags worked for a while then stopped however.

Upvotes: 0

Related Questions