I’m building a site on the new Razor engine that comes with MVC 3 (and loving the new syntax!). However, I am at a loss about using public properties / constants with it. I know that with WebForms we could add a public property in code behind:
public string ImageFolder { get; set; }
I would like to define important variables in one global place that my views can access, starting with paths to CSS files and images:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
var ContentFolder = "~/Content";
var CssFolder = ContentFolder + "/Stylesheets";
var ImageFolder = ContentFolder + "/Images";
}
I have tried putting the above code block in _Layout, as well as inside _ViewStart. However, accessing them from child views fails miserably. I thought of defining a public property in the above code block but it doesn’t compile.
Solutions?
- As far as I have seen, noone uses code behind with Razor.
- I guess I should be able to inherit from the default view and define my properties there (as described on Stack).
But I’m strongly hoping that there should be an easier way to do something so simple?
Your can create a folder “App_Code” and create a file “GlobalVal.cshtml”.
bellow is a sample code in the file:
and bellow is a sample using it: