Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a simple Viewbag.Title, getting a RuntimeBinderException

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!

like image 385
JohnC1 Avatar asked Dec 31 '13 19:12

JohnC1


2 Answers

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()

like image 102
Kaido Avatar answered Oct 18 '22 13:10

Kaido


i tried this and it works for me:

@(ViewBag.GetType().GetProperty("Title") == null ? "" : ViewBag.Title)

it's an old question but maybe it helps someone.

regards.

like image 1
Muzaffer Galata Avatar answered Oct 18 '22 13:10

Muzaffer Galata