203

How do I access a key value from web.config in my Razor view.

This is in my web.config in the Web Project root level.

 <appSettings>
   <add key="myKey" value="MyValue"/>
</appSettings>

I want to have to use the key in my Razor view.

Thank you.

Peter David Carter
  • 2,548
  • 8
  • 25
  • 44
Hari Gillala
  • 11,736
  • 18
  • 70
  • 117
  • 11
    @sathish Kumar: I thought it is bit different in MVC, so I had to ask in here, So it very worst question you voted it down. Remember you have alos started your career as begineer, be polite and respect others. I could not find this kind of question in google search.. Razor is new.. – Hari Gillala Jan 31 '12 at 10:39
  • 1
    Sorry about that.As per the stackoverflow FAQ i did.For this question i had many results from google.If i did anything wrong once again sorry. – sathishkumar Jan 31 '12 at 11:36

4 Answers4

272
@System.Configuration.ConfigurationManager.AppSettings["myKey"]
Anwar
  • 4,470
  • 4
  • 24
  • 30
  • Have a look at Peter's answer, since in this one you have to add reference ConfigurationManager – sensei Nov 07 '17 at 12:43
256

The preferred method is actually:

@System.Web.Configuration.WebConfigurationManager.AppSettings["myKey"]

It also doesn't need a reference to the ConfigurationManager assembly, it's already in System.Web.

Peter J
  • 57,680
  • 8
  • 38
  • 45
  • 5
    What's the difference between @Anwar's answer and yours? Besides the naming ;) – Nate-Wilkins Oct 11 '13 at 16:40
  • 24
    System.Configuration might need to be referenced separately if it's not used elsewhere in your project, but System.Web is already referenced in an MVC project. – Peter J Oct 11 '13 at 17:17
16

Here's a real world example with the use of non-minified versus minified assets in your layout.

Web.Config

<appSettings>

   <add key="Environment" value="Dev" />

 </appSettings>

Razor Template - use that var above like this:

@if (System.Configuration.ConfigurationManager.AppSettings["Environment"] == "Dev")
{    
    <link type="text/css" rel="stylesheet" href="@Url.Content("~/Content/styles/theme.css" )">    

}else{        

   <link type="text/css" rel="stylesheet" href="@Url.Content("~/Content/styles/blue_theme.min.css" )">    

}
Peter Drinnan
  • 4,344
  • 1
  • 36
  • 29
  • 5
    Even if it's nice with real life examples, using minification that way with .net MVC is a shame. Have a look at bundling http://www.asp.net/mvc/overview/performance/bundling-and-minification – Crypth Dec 19 '14 at 14:16
2

FOR MVC

-- WEB.CONFIG CODE IN APP SETTING -- <add key="PhaseLevel" value="1" />

-- ON VIEWS suppose you want to show or hide something based on web.config Value--

-- WRITE THIS ON TOP OF YOUR PAGE-- @{ var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString(); }

-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.

@if (phase != "1") { @Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml") }

raj joshi
  • 21
  • 2