Reputation: 173
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
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.
Upvotes: 2
Views: 910
Reputation: 3425
You could also just create a class file inside the App_Code folder (like Helpers.cs or something) - whatever functions placed in that class should be available throughout your project, and naturally there would be only one place to maintain the code.
Upvotes: 2