Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Petras Surna 90 posts 144 karma points
    Apr 05, 2011 @ 07:56
    Petras Surna
    0

    Can you call a C# method within Razor (similar to XSLT extension)

    I have this Razor code:


    @foreach(var page in Model.Children) {
      <li>
        @page.Name
      </li>
    }

    But how can I pass @page.Name to a C# method to modify it if I have to?

    How can I do this:

    @foreach(var page in Model.Children) {
      <li>
        @ModifyPageName(@page.Name)
      </li>
    }

    Is this possible?

  • Sebastiaan Janssen 5045 posts 15476 karma points MVP admin hq
    Apr 05, 2011 @ 08:08
    Sebastiaan Janssen
    0

    Yes you can use anything that you normaally use in .net, for example: MyClass.DoSomething(@page.Name).

  • Petras Surna 90 posts 144 karma points
    Apr 05, 2011 @ 08:20
    Petras Surna
    0

    Yes, I got it to work just now!

    For a newbie, do this:

    1. Create a Visual Studio class library project.

    2. Add your classes in there eg

    namespace ActiviaExtensions
    {
      public class BlogMethods
      {
        public static string Test(string blogDetails)
        {
          return blogDetails.Length.ToString();
        }
      }
    }

    3. ftp the dll to your Umbraco bin directory

    4. Call it in your Razor script:


     @BlogMethods.Test(@blogpost.postBody.ToString())

  • Petras Surna 90 posts 144 karma points
    Apr 05, 2011 @ 08:21
    Petras Surna
    0

    And add a using at the top of the Razor file:

    @using ActiviaExtensions;

  • Alex 78 posts 136 karma points
    Apr 05, 2011 @ 09:33
    Alex
    0

    You could also set up Razor Helper methods and drop them into the App_Code folder to make them Globally available to your scripts. See this post for an example

    http://joeriks.wordpress.com/2011/03/11/better-structure-for-your-razor-scripts-with-renderpage-in-umbraco/

Please Sign in or register to post replies

Write your reply to:

Draft