Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot perform runtime binding on a null reference. ViewBag.Title is null

I want to provide a simple general functionality to show a message at the top of a page whenever I need to inform a user that operation is successful. My solution would be to put an object into ViewBag.Info that contains details about a message, including bool public IsMessage;and read it in _Layout.cshtml where I have an extra hidden div.

The way I am trying to do it in _Layout.cshtml is I put what's in @(ViewBag.Info.IsMessage (false/true) into a hidden field and read it by JavaScript. If the field contains "true", javascript will invoke a function ShowEvent().

For some reason, if I add the line @(ViewBag.Info.IsMessage.ToString().ToLower()) VS2010 complains about ViewBag.Title in _Layout.cshtml.

"Cannot perform runtime binding on a null reference"

The code of _Layout.cshtml is simple:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <link rel="Stylesheet" type="text/css" href="@Url.Content("~/Content/StyleSheet.css")" />
    <script src="~/Scripts/jquery-2.1.1.min.js" type="text/javascript"></script>
    <title>@ViewBag.Title</title>
</head>
<body>
    <input type="hidden" id="is-event" name="is-event" value="@(ViewBag.Info.IsMessage.ToString().ToLower())"/>
    <div class="recent-events"></div>
    <div>
        @if (IsSectionDefined("loginfo"))
        {
            @RenderSection("loginfo", false)
        }
        @RenderBody()
        @if (IsSectionDefined("Home"))
        {
            @RenderSection("Home", false)
        }
    </div>
</body>
</html>

And the code of the View Index.cshtml is:

@model TestProject.ViewModels.Account.UserData
@{
    ViewBag.Title = "Index";
    string identityName = HttpContext.Current.User.Identity.Name;
    string userrole = Model.UserRoles.FirstOrDefault();
}

<h2>Index</h2>
<br />

As you can see ViewBag.Title is defined.

EDIT. The code of the controller:

public ActionResult Index()
{
    // ...
    InfoModel infoModel = new InfoModel()
    {
        IsMessage = true, Duration = 3000, Message = "Logging in successfull", BackgroundColor = "#bbffbb"
    };
    ViewBag.Info = infoModel;
    ViewBag.Title = string.Empty;
    return View(userdata);
}
like image 559
Celdor Avatar asked Sep 28 '22 22:09

Celdor


1 Answers

You can get this issue if you attempt to reference a Model from a View which isn't strongly typed. For instance, typing

@Model.ID 

somewhere in the page will attempt to bind to the ID property of the ViewModel - if you haven't defined the model type at the top of the View page with

@model MyModel 

then it will bomb out with this obscure error message.

like image 85
Steve Woods Avatar answered Oct 05 '22 08:10

Steve Woods