I am learning Umbraco 7 and want to build a library of common Razor functions.
My idea was to have a core partial view which would be included on most templates and this partial view would have an @functions{} block.
I would then be able to call these functions from the main templates. However, this doesn't seem to work - presumably it's a scope issue.
I have tried using ViewBag and ViewData but changing them in the partial doesn't get returned to the template.
In other words, it seems I can pass parameters and page properties to a partial view, but can't pass anything back to the calling template?
The functions would be various, including string manipulation on the page content (eg string replace) the idea being the function would have parameters of the property in question, some text to replace with and then return the result to the template for outputting, so other ideas include
- the partial view updates the page properties which can then be output by the template (is this possible?)
- passing parameters to the partial (including one to say which function to use) and have the partial itself output the result of the function to the browser. However, as I might want to use the functions on more than one property on the page, it would mean including the partial view multiple times, once for each property. Would this cause problems?
- putting the function on the master template and calling from the child templates (doesn't work)
Or is there a better way that I am missing.
To sum up, what I am trying to do (without amending controllers or any part of the MVC - ie using Umbraco out of the box), is have generic functions stored centrally that I can call on templates to manipulate the page content before sending it to the browser.
Suggestions / links gratefully received.
[Edit]
Found a possible solution : add functions to cshtml file in App_Code and refer to by file name
eg
myFunctions.cshtml has function myFn(...
so in template @myFunctions.myFn(...
Is this a robust solution?
The downside is any changes immediately affect the whole site, so any bug is a problem throughout, whereas a partial view solution would only affect templates where used.