如何在 MVC5 中使用会话或应用程序声明全局变量

How to Declare global Variable Using Session or Application in MVC5

我需要一些帮助,了解如何使用来自数据库的值声明一个全局变量...

我在应用程序中有两个具有不同_Layout 的分支,我根据来自数据库的类别 ID 使用布局渲染视图,现在我想要一种情况,当用户登录应用程序时,主布局显示两个分支,当用户选择一个分支时,我想从数据库中获取该分支的类别 ID 并将其存储在 HttpContext.Session["CategoryID"] 或 HttpContext.Application["CategoryID"] 这样我就可以使用这个变量并在整个应用程序中呈现适当的布局,除非用户返回主菜单并选择另一个分支,然后该值才能更改并呈现具有所有视图的不同布局。

这是我尝试过的方法,但它不起作用

//GET: /Branch/
    public ActionResult Index(int id)
    {
        var BranchId = _schoolService.getBranchById(id).SchoolCategoryId;

        HttpContext.Session["BranchId"] = BranchId;
        HttpContext.Application["BranchId"] = BranchId;

        int branch = (int)HttpContext.Session["BranchId"];

        if (branch == 1)
        {
            return View("Index", "~/Views/Shared/_LayoutBranch.cshtml");
        }
        else if (branch == 2)
        {
            return View("Index", "~/Views/Shared/_LayoutSecodary.cshtml");
        }
        else
            return RedirectToAction("Error");

    }

尝试从分支控制器的入口存储变量,以便我可以在任何视图和控制器中调用它。

甚至尝试使用 BaseController 并在其他控制器中继承它,但它仍然无法正常工作。

请问我是不是遗漏了一些东西,或者有没有其他方法可以让它按照我想要的方式工作,请帮助并感谢您抽出时间...

我用硬编码的 BranchId=1 测试了你的代码,它有效。至少对于 Index() 操作,但我想您希望它适用于每个控制器中的所有操作。

尝试这样的事情:

搜索 ~/_ViewStart.cshtml 并将内容替换为:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";

    string layoutId = HelperMethods.GetLayoutId();

    if(layoutId != null) {
        switch(HelperMethods.GetLayoutId())
        {
            case "1":
                Layout = "~/Views/Shared/_Layout1.cshtml";
                break;
            case "2":
                Layout = "~/Views/Shared/_Layout2.cshtml";
                break;
        }
    }
}

_ViewStart.cshtml 指定每个视图的布局文件,它本身并不指定。因此,将您的代码写入此文件会导致整个应用程序采用一种布局,具体取决于您的分支事物。注意:为了使这个起作用,在 ~/Views/folder/file.cshtml 下的视图文件中不能有任何 Layout 分类.

编辑: 您可以使用一些静态方法来设置或获取布局 ID。例如,单击一个按钮会调用 SetLayoutId(1),然后在 _ViewStart.cshtml 中您会从会话中收到它。

using System.Web;

namespace SomeMVC
{
    public static class HelperMethods
    {
        public static string GetLayoutId()
        {
            return (string) HttpContext.Current.Session["LayoutId"];
        }

        public static void SetLayoutId(string id)
        {
            HttpContext.Current.Session["LayoutId"] = id;
        }
    }
}