ViewBag declaration on controller

I use ViewBag.Message with the same message several times in controller methods. Can I declare ViewBag.Message at the top of the class, so can it be used throughout the controller without repeating the code?

+2
source share
1 answer

Assuming Razor syntax, you can achieve this with.

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

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

 <h1>@pageMessage</h1> 

EDIT

The ViewBag is a dynamic object that is a member of the Controller base class, so just specify this once in the entire controller, you can put something in your controller constructor.

 public class MyController : Controller { public MyController() { ViewBag.ViewTime = DateTime.Now.ToString(); } // rest of controller code } 
+3
source

Source: https://habr.com/ru/post/1011863/


All Articles