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:
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With