Question

Specifically, I have a phone number that is used in a bunch of views(and a couple actions), and I would like to centralize that somewhere in case it changes. Is web.config good enough? Is there a better place for this? Ideally, I wouldn't have to recompile if the value changed. Thanks!

Update: So far, I like the partial view the best, the main reason being no recompile, no adding it to viewmodels. Another option I've explored is Application_Start in global.asax and using the Application dictionary(although it sounds like the use of this dictionary is frowned upon in mvc). One thing to note is that I need to use this number in some actions also. Any more thoughts/opinions?

Was it helpful?

Solution

In no uncertain terms do you want a view accessing your web.config file.

If this is something which shows up in many places in your views and requires a static set variable, then make a partial view to display the number, and call the partial view multiple times.

The advantage is that you are keeping it in a re-usable area so that if you change it once, it changes everywhere, and also that you are not going to have any separation of concern violations by having your view make calls where it shouldn't have access. Updating the partial will also not require a re-compile.

/Shared/_PhoneNumberPartial.cshtml

<span>555-1234</span>

Used in a view

<div>Phone Number<br/>
 @Html.Partial("_PhoneNumberPartial")
</div>

OTHER TIPS

For this case specifically, I would save it in class file. but the best solution depends on the project, later scale of it, and etc, etc.

For something like a phone number I'd put it in a data storage of some kind. If you don't need a full database consider something simple like a file based storage or even a simple *.json or *.xml file, preferably in the AppData folder. However if you do this you should be passing it to your view via a ViewModel and let your controller or some other method do the actual reading from your data storage. Views should not access these directly.

I find the web.config is best suited for configuration settings. It is a config file after all. It's not the best place to put content. Your phone number is content, and to me Content should be in a dynamic and structured location.

You can add the phone number to appSetting key/value in web config like below:

<appSettings>
     <add key="PhoneNum" value="1234567890"/>
 </appSettings>

Then you can use it

using System.Configuration;
string Phone = ConfigurationManager.AppSettings["PhoneNum"].ToString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top