is it possible to Access my Project Properties within the .cshtml Razor file?
I need something like this:
@if (myProject.Properties.Settings.Default.foo) {...}
while foo is a boolean
I get the error that because of a security reason it is not possible.
You shouldn't really be calling ConfigurationManager
directly from your view. Views should be 'dumb' in MVC, ie not have any knowledge of the data structure or back-end, and by calling ConfigurationManager
directly your view knows too much about how your settings are stored. If you changed your settings to use a different store (ie a database) then you'd have to change your view.
So, you should grab that value elsewhere and pass it to your view so your view just takes care of rendering it and that's it. You probably have 2 options:
- Add something into the ViewBag and grab it in the view
- Render an action from a common controller that passes a strongly typed ViewModel to a partial view.
I'd discourage option 1 because in general it is good to avoid the ViewBag
because it isn't strongly typed (Is using ViewBag in MVC bad?). Also, to do this you'd either have to inherit from a BaseController
for every controller which can be a pain, or create a global action filter that overrides ActionExecuted
and stuffs something in the ViewBag
there.
Option 2 is probably better. I'd create a common controller something like:
public class CommonController : Controller
{
[ChildActionOnly]
public ViewResult Settings()
{
// Get some config settings etc here and make a view model
var model = new SettingsModel { Foo = myProject.Properties.Settings.Default.foo };
return View(model);
}
}
Then in your layout file you can call:
@Html.Action("Settings", new { controller = "Common" })
Which renders a strongly-typed partial view (~/Views/Common/Settings.cshtml) which looks like:
@model YourProject.Models.SettingsModel
@if(Model.Foo)
{
// So something
}
That way you are still using a strongly typed model and view, your layout view stays clean and simple and your partial view remains 'dumb'
The app settings are stored in the web.config file as
<applicationSettings>
<YourProject.Properties.Settings>
<setting name="Setting" serializeAs="String">
<value>asdqwe</value>
</setting>
so you can try use ConfigurationManager.AppSettings dictionary like
ConfigurationManager.AppSettings["Setting"]