207

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.

2
  • 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.. Commented Jan 31, 2012 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. Commented Jan 31, 2012 at 11:36

4 Answers 4

277
@System.Configuration.ConfigurationManager.AppSettings["myKey"]
Sign up to request clarification or add additional context in comments.

1 Comment

Have a look at Peter's answer, since in this one you have to add reference ConfigurationManager
261

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.

2 Comments

What's the difference between @Anwar's answer and yours? Besides the naming ;)
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.
17

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" )">    

}

1 Comment

Even if it's nice with real life examples, using minification that way with .net MVC is a shame. Have a look at bundling asp.net/mvc/overview/performance/bundling-and-minification
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") }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.