在控制器上声明ViewBag [英] Declare ViewBag on controller

查看:97
本文介绍了在控制器上声明ViewBag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制器上的方法中多次使用具有相同消息的ViewBag.Message。
可以在类的顶部声明ViewBag.Message,因此可以在整个控制器中使用它而无需重复代码?

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?

推荐答案

假定使用Razor语法,您可以使用

Assuming Razor syntax you can achieve this with.

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

然后pageMes​​sage是该页面可用的局部变量,例如:

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

<h1>@pageMessage</h1>

编辑

ViewBag是一个动态对象,它是Controller基类的成员,因此只需在整个控制器中指定一次即可,您可以在控制器构造函数中添加一些内容。

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
}

这篇关于在控制器上声明ViewBag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆