如何在MVC3中使用全局变量

时间:2014-02-19 08:02:38

标签: c# asp.net-mvc asp.net-mvc-3

我在model.cs中为GlobalVarables声明了一个类,在同一个模型中还有一个类代表我在数据库中的表。

namespace Project.Models
{
    [Table("REGIONS")]
    public class DBTable
    {
    // table columns{get;set;}
    }

    public static class MyViewModel
    {
        public static string vVar1{get; set;} 
        public static string vVar2{get; set;} 
    }

然后在Controller中表示。

namespace Project.Controllers
{ 
    public class ProjectController : Controller
    {
        public ActionResult DisplayVariables(MyViewModel model)
        {

            model.Var1 = "testString";          
            return View(model);
        }

        ....
    }
}

index.cshtml代码在这里

@model IEnumerable<sLightcSharp.Models.Region>

如何包含第二个模型

@model IEnumerable<sLightcSharp.Models.MyViewModel>

如何在index.cshtml中使用Var1变量。

2 个答案:

答案 0 :(得分:2)

这取决于天气这些变量是否会在应用程序生命周期中的某个时间发生变化! 假设它们是静态的,它们永远不会改变,那么你会有类似的东西

namespace Utilities
{
    public class Constants
    {
        public static readonly string DBCONTEXT_KEY = "dbcontext";
        public static readonly string COMPANY_ID = "COMPANY_ID";
        public static readonly string ESTABLISHMENT_ID = "ESTABLISHMENT_ID";
        public static readonly string USER_ID = "USER_ID";
    }
}

使用razor语法

在视图中调用变量的方式非常简单
@Utilities.Constants.COMPANY_ID

和asp语法的旧方式

<%=Utilities.Constants.COMPANY_ID %>

但通常我在Session键或一些Dictionary键中使用这种类,如

HttpContext.Current.Items[Constants.DBCONTEXT_KEY]

HttpContext.Current.Session[Constants.USER_ID]

答案 1 :(得分:0)

你可以做的是创建一个单身人士,我在我的网站中使用单身人士来缓存一些基本的东西。

 public class Configuration
    {
        private static Configuration _me;

        public static Configuration Settings
        {
            get
            {
                if (_me == null)
                {
                    _me = new Configuration();
                }
                return _me;
            }
        }

        // Properties
        public string Title { get; set; }
        public string Description { get; set; }
   }
}

然后您可以使用以下方式获取/设置信息:

Configuration.Settings.Variable = "Test";
相关问题