2014-09-25 61 views
2

我有一個MVC 4/C#/ .NET網站,其他人設置,我正在管理。我有一個HomeController和ArticleController。我正在尋找一種方法來在一個地方定義文章的名稱,並將其全部使用。具體而言,在Index.cshtml(通過HomeController調用)以及通過ArticleController.cs調用的所有文章(Article_1,Article_2等)。C#中的全局變量替代?

我原來的計劃是定義一個全局變量(我用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#不是好事,我想知道全局變量是否可行。如果你同意這一點,我應該怎麼做到這一點?

+0

爲什麼不使用''

@Globals.story_1_title
? – 2014-09-25 19:25:14

+0

「那沒有用」是什麼意思?我的猜測是你的問題是這個神祕的「寫」方法,你有... – 2014-09-25 19:25:40

回答

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(); 
     } 
    } 
+0

+1,但這幾乎看起來像一個完整的'杜'概念。當我讀到我在想的問題時,'呃,爲什麼這不是配置設置?' – 2014-09-25 19:38:31

+0

@JoelEtherton - 我覺得同樣的方式,幾乎沒有作爲一個答案發布思考我沒有正確閱讀它。但是,我知道我有時會忘記做事的「更容易」的方式:) – Tommy 2014-09-25 19:40:02

0
var abc= '@System.Configuration.ConfigurationManager.AppSettings["abc"]';