Search code examples
asp.net-mvcrazor

Razor function: What is the difference between @helper and @functions


Few question about razor function in asp.net mvc.

1) see the code below

@helper WelcomeMessage(string username)
{
    <p>Welcome, @username.</p>
}

Then you invoke it like this: @WelcomeMessage("John Smith")

@functions{
    public string GetSomeString(){
        return string.Empty;
    }
}

see there is two razor function. in one @helper is used to declare razor function and in second one @functions. so tell me what is the difference between @helper and @functions ?

2) can we declare razor function in .cs code...if yes then is there any convention we need to follow ?

3) can we return integer from razor function

@helper Calculator(int a, int b)
{
    @{
        var sum = a + b;
    }
    <b>@sum</b>
}

@Calculator(1, 2)

can we return sum to its calling environment?


Solution

  • Both are for the purpose of Reusability.

    But @functions are used when there is no html needed to be returned back and we only want to do some calculations or some business logic which means we need to write purely C# code.

    For @functions we could use them when we don't want to return html back in the view. If we want to return Html from the @functions we will need to specifically return HtmlString from it instead of String and for @functions we will also need to specify and include the namespaces in it if we want to return HtmlString like:

    @using System.Web.Mvc;
    @functions {
    
       public static HtmlString WelcomeMessage(string username)
       {
        
           return new HtmlString($"<p>Welcome, {username}.</p>");
       }
    }
    

    And @helper is useful when we want to create html and render it with some logic which means that we need to write razor code.

    For @helper they are used when our method we are defining needs to be mixed with Html and we want to return some html back.

    @helper{
    
       public WelcomeMessage(string username)
       {
        
           <p>Welcome, @username.</p>;
       }
    }
    

    Please read the following great post which explains in detail the differences of both:

    https://www.mikesdotnetting.com/article/173/the-difference-between-helpers-and-functions-in-webmatrix