Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewBag - Object reference not found - MVC 3

Upon publishing my MVC 3 Web Application to my website I get an error stating an Object reference not set to an instance of an object.

The 'error' line is: Line 2: ViewBag.Title = "Index";

This is my Index view:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

This is my Home Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

    }
}

I have uploaded DLL's:

System.Web.Helpers
System.Web.Mvc
System.Web.Razor
System.Web.WebPages
System.Web.WebPages.Deployment
System.Web.WebPages.Razor

Thanks for any assistance

like image 681
ElveMagicMike Avatar asked Dec 02 '22 23:12

ElveMagicMike


2 Answers

I hit the same ViewBag error. in my case Model was null but the exception was directing to viewbag row.

When I passed a model to view error fixed.

like image 51
Serdar Avatar answered Dec 22 '22 13:12

Serdar


When you look in /Views/Shared/_Layout.cshtml, you will probably see something like this:

<title>@ViewBag.Title</title>

It is assuming this property has been set somewhere. Usually, you set this in your child views. So the easiest solution is to modify your Index.cshtml view so that it resembles something like this:

@{
     ViewBag.Title = "Title of the page";
     Layout = "~/Views/Shared/_Layout.cshtml";
}
like image 42
Kristof Claes Avatar answered Dec 22 '22 12:12

Kristof Claes