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

标签 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# 不利,我想知道全局变量是否是正确的选择。如果您同意这一点,我应该如何实现这一点?

最佳答案

也许我误解了您想要的内容,但为什么不使用您的 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/

相关文章:

c# - 从 NetworkStream 读取 BinaryFormatter 序列化对象的最有效方法?

c# - 领域驱动设计问题

jQuery 调用 Controller 未命中断点

asp.net-mvc - 从区域调用部分 View

javascript - 如何将带有查询字符串的当前 Url 传递给 MVC 中的 Html.ActionLink() 函数

android - 带防伪、token、cookie 和参数的 Http post

c# - 从字节中获取值

c# - 仅检测来自 Kinect 正前方用户的语音

c# - 使用 Json.NET 将 Json 字符串发布到远程 PHP 脚本

c# - 如何将 404 错误从 MVC 4 中的模型传递到 View