[英]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.