asp.net-mvc - Controller 静态方法中的ViewBag

标签 asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我是 mvc 的新手,我在 Controller 方法中加载 ViewBag,

HomeController: Controller
{
    Public ActionResult Index()
    {
        loadViewBag();
        return View();
    }

    public void loadViewBag()
    {
      ViewBag.aaa = "something";
    }
}

它工作正常。

我的问题是,现在我想从另一个 Controller (比如帐户)调用 loadViewBag() 方法,这样我就可以重用相同的方法,并且由于一些静态变量需要使 loadViewBag() 方法静态化,例如: public static void loadViewBag() 如果我将 loadViewBag 方法设为静态,ViewBag 上会出现错误“非静态字段、方法或属性‘System.Web.Mvc.ControllerBase.ViewBag.get’需要对象引用” .

有什么解决方案/建议吗

谢谢。

最佳答案

只需将其作为 ControllerBase 的扩展方法,例如

public static void ControllerExt
{
    public static void LoadViewBag(this ControllerBase controller)
    {
        controller.ViewBag.aaa = "something";
        ...
    }
}

这样你就可以在任何 Controller 中使用它了

public class HomeController : Controller
{
    public ActionResult Index()
    {
        this.LoadViewBag();
        return View();
    }
}

public class AccountController : Controller
{
    public ActionResult Index()
    {
        this.LoadViewBag();
        return View();
    }
}

如果它只特定于一些 Controller ,那么传递 ViewBag 属性会更灵活,例如

public static class ControllerHelper
{
    public static void LoadViewBag(dynamic viewBag)
    {
         viewBag.aaa = "something";
    }
}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ControllerHelper.LoadViewBag(ViewBag);
        return View();
    }
}

关于asp.net-mvc - Controller 静态方法中的ViewBag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18783357/

相关文章:

asp.net-mvc-4 - 如何在mvc布局中添加标志?

asp.net-mvc - 如何从 ASP.NET MVC Web API 帖子中获取原始 JSON 字典?

javascript - 停止在加载时调用 Html.Action

html - 在 asp.net mvc 中滚动没有滚动条的 Div?

ssl - Azure 网站自定义 SSL ASP.Net MVC 解决方法

c# - ASP.NET MVC 4 一些路由不工作

c# - 如何在剑道下拉列表中绑定(bind)字符串列表

c# - C# 中的 Google map API 地址验证

jquery - MVC3 jquery.validate.unobtrusive 覆盖选项而不编辑源代码?

c# - 如何在 .net 中获取当前语言环境的默认小数点/千位分隔符