MVC – Using Global Constant Values Throughout the Site

mvc

My MVC (.NET) has some constant values through out the site, such as the phone number, physical address, email address etc.

I'd like to store this value once, so future updates are easier for when they change their details.

To make my question simpler, I've only focused on phone number.

My question is where and how to store this number and a problem I'm facing with my decision. At the moment, I've chosen to store it in the Global.asax file as a static method, eg

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
       //logic
    }

    public static string GetPhoneNumber()
    {
        return "012345 678 910";
    }
}

This works very well, in my controller I can add references to this method and assign it to a ViewBag

  public ActionResult Contact()
  {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
  }

As per many sites, the phone number will be visible at the top of every page and as such, placing it in the _Layout.cshtml is logical.

The problem I have is there is no controller (not that I know) for the _Layout.cshtml and the only way I can pass the value is to have a ViewBag.Phone set up for every view, EG

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
        return View();
    }

    public ActionResult About()
    {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
        return View();
    }

This is messy and smelly but I have no idea how I can improve this.

Should I be storing my global variables in a different place or is there a better approach for this as I'm sure this is a common problem.

Best Answer

Store the values in web.config:

<appSettings>
  <add key="CompanyTelNo" value="012345 678 910" />
</appSettings>

Then in your code, you can reference it with:

ConfigurationSettings.AppSettings["CompanyTelNo"];

However, since that's actually deprecated, it's better to use:

ConfigurationManager.AppSettings["CompanyTelNo"]
Related Topic