Reputation: 14054
I have an MVC 4 / C# / .NET website that someone else set up, that I'm managing. I have a HomeController and ArticleController. I am looking for a way to define the name of an article in one place and use it all over. Specifically though, in Index.cshtml (called via HomeController) and all the articles (Article_1, Article_2, etc.) called via ArticleController.cs.
My original plan was to define a global variable (I used this SO article to set it up):
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 didn't work though, so if you think globals are the way to go, let me know what I'm doing wrong here.
But, upon reading this article, which basically says reliance on global variables is not good for C#, I'm wondering if globals are the way to go. If you agree with that, How should I accomplish this?
Upvotes: 2
Views: 952
Reputation: 389
var abc= '@System.Configuration.ConfigurationManager.AppSettings["abc"]';
Upvotes: 0
Reputation: 39807
Maybe I am misinterpreting what you want, but why not use your web.config file to hold the static information that you need and reference it from there.
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();
}
}
Upvotes: 3