In a simple Viewbag.Title, getting a RuntimeBinderException

JohnC1 picture JohnC1 · Dec 31, 2013 · Viewed 7k times · Source

I have a really simple ViewBag.Title. Like this:

@{
    ViewBag.Title = "My Title";
    ViewBag.MiniTitle = "Sub - Title";
}

Which is being parsed on _Layout.cshtml, on the

<title>@ViewBag.Title</title>

However, I am getting this exception:

Thrown: "'System.Dynamic.DynamicObject' does not contain a definition for 'Title'"
(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) 
Exception Message = "'System.Dynamic.DynamicObject' does not contain a definition for 
'Title'", Exception Type = "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException"

I been searching and I could not find much information about it. It is basically the same issue this guy was facing: http://forums.asp.net/t/1715878.aspx?MVC3+Razor+Viewbag+Title+RuntimeBinderException

My issue is also the same as last guy that posted. This does not cause any problems for me, projects works fine and so does my titles. However, I am not liking the fact that an exception is being thrown due to the fact they are expensive.

Does anyone know how can i fix this issue? Thanks!

Answer

Kaido picture Kaido · Mar 13, 2015

Could be that you are using @ViewBag.Title before you declare it, for example if your layout file has

<title>@ViewBag.Title</title>

but you define the title LATER in a partial view or similar

@{
    ViewBag.Title = "My Title";
    ViewBag.MiniTitle = "Sub - Title";
}

try setting ViewBag.Title in the controller action, so that is available before you call View()