Access key value from Web.config in Razor View-MVC3 ASP.NET

asp.net Mvc-3

asp.net Mvc-3 Problem Overview


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.

asp.net Mvc-3 Solutions


Solution 1 - asp.net Mvc-3

@System.Configuration.ConfigurationManager.AppSettings["myKey"]

Solution 2 - asp.net Mvc-3

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.

Solution 3 - asp.net Mvc-3

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

}

Solution 4 - asp.net Mvc-3

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHari GillalaView Question on Stackoverflow
Solution 1 - asp.net Mvc-3AnwarView Answer on Stackoverflow
Solution 2 - asp.net Mvc-3Peter JView Answer on Stackoverflow
Solution 3 - asp.net Mvc-3Peter DrinnanView Answer on Stackoverflow
Solution 4 - asp.net Mvc-3raj joshiView Answer on Stackoverflow