[英]Global Variable Alternatives in C#?
我有一個別人正在建立的MVC 4 / C#/ .NET網站,我正在管理。 我有一個HomeController和ArticleController。 我正在尋找一種方法來在某處定義文章的名稱並在各處使用它。 但是,特別要注意的是,在Index.cshtml(通過HomeController調用)中,以及所有文章(Article_1,Article_2等)都通過ArticleController.cs調用。
我最初的計划是定義一個全局變量(我使用這篇SO文章進行了設置):
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>
不過,這沒有用,因此,如果您認為要走全球路線,請讓我知道我在這里做錯了什么。
但是,在閱讀了這篇文章 (基本上說依賴全局變量對C#不利)后,我想知道是否可以使用全局變量。 如果您同意,我應該如何做到?
也許我在誤解您想要的內容,但是為什么不使用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();
}
}
var abc= '@System.Configuration.ConfigurationManager.AppSettings["abc"]';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.