C#中的全局变量替代品?

时间:2014-09-25 19:18:40

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

我有一个其他人设置的MVC 4 / C#/ .NET网站,我正在管理。我有一个HomeController和ArticleController。我正在寻找一种方法来在一个地方定义一篇文章的名称并全部使用它。具体来说,在Index.cshtml(通过HomeController调用)和通过ArticleController.cs调用的所有文章(Article_1,Article_2等)。

我最初的计划是定义一个全局变量(我使用this SO article来设置它):

HomeController中:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyStie.Controllers
{
    public class Globals
    {
        public static article_1_title = "This will show up all over the place";
    }
    public class HomeController : Controller //This is basically the same as ArticleCont.
    {
        public ActionResult Index()
        {
            retrurn View();
        }
    }
}

Index.cshtml:

<div>@{Write(Globals.story_1_title)}</div>

虽然这不起作用,所以如果你认为全局变形是可行的,请告诉我这里我做错了什么。

但是,在阅读this article时,基本上说依赖全局变量对C#不利,我想知道全局变量是否可行。如果您同意,我应该如何做到这一点?

2 个答案:

答案 0 :(得分:3)

也许我误解了你想要的东西,但为什么不使用你的web.config文件来保存你需要的静态信息并从那里引用它。

<强>的Web.config

<configuration>
   <appSettings>
       <add key="ArticleTitle" value="This will show up everywhere"/>
   </appSettings>
</configuration>

<强>控制器

 public class HomeController : Controller //This is basically the same as ArticleCont.
    {
        public ActionResult Index()
        {
            ViewData["ArticleTitle"] = ConfigurationManager.AppSettings["ArticleTitle"];
            retrurn View();
        }
    }

答案 1 :(得分:0)

var abc= '@System.Configuration.ConfigurationManager.AppSettings["abc"]';
相关问题