Declare ViewBag on controller

孤者浪人 提交于 2019-12-12 18:07:42

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/9930797/declare-viewbag-on-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!