我有一个由其他人建立并由我管理的 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# 不利,我想知道全局变量是否是正确的选择。如果您同意这一点,我应该如何实现这一点?
最佳答案
也许我误解了您想要的内容,但为什么不使用您的 web.config 文件来保存您需要的静态信息并从那里引用它。
Web.config
<configuration>
<appSettings>
<add key="ArticleTitle" value="This will show up everywhere"/>
</appSettings>
</configuration>
Controller
public class HomeController : Controller //This is basically the same as ArticleCont.
{
public ActionResult Index()
{
ViewData["ArticleTitle"] = ConfigurationManager.AppSettings["ArticleTitle"];
retrurn View();
}
}
关于c# - C# 中的全局变量替代品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26046401/