Declare ViewBag on controller
Asked Answered
S

1

2

I'm using ViewBag.Message with the same message several times into the methods on the controller. It is possible to declare ViewBag.Message on the top of the class, so can be used in the whole controller without repeat the code?

Swish answered 29/3, 2012 at 17:57 Comment(0)
D
4

Assuming Razor syntax you can achieve this with.

@{string pageMessage = ViewBag.Message.ToString();}

then pageMessage is a local variable available to the page, for example:

<h1>@pageMessage</h1>

EDIT

ViewBag is a dynamic object which is a member of the Controller base class so to just specify this once in the whole controller you could put something in your controller constructor.

public class MyController : Controller
{
        public MyController()
        {
            ViewBag.ViewTime = DateTime.Now.ToString();
        }

        // rest of controller code
}
Dickey answered 29/3, 2012 at 18:25 Comment(1)
I'm talking about the code on the controller, not on the viewSwish

© 2022 - 2024 — McMap. All rights reserved.