247

I need to create a function that is only necessary inside one cshtml file. You can think of my situation as ASP.NET page methods, which are min web services implemented in a page, because they're scoped to one page. I know about HTML helpers (extension methods), but my function is just needed in one cshtml file. I don't know how to create a function signature inside a view. Note: I'm using Razor template engine.

1

6 Answers 6

466

why not just declare that function inside the cshtml file?

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

<h2>index</h2>
@GetSomeString()
15
  • 37
    This should be marked as the answer, as the @functions directive specifically meets the OP requirements. The Helpers feature is intended for shared use across multiple template files by putting the file with the @helper directive into an App_Code directory. Whereas, the @functions directive allows a function to be used only by the template that declares it.
    – Jon Davis
    Jul 4, 2011 at 21:24
  • 7
    Also note helpers seem oriented to returning strings just like other razor helpers already do, and thus the functions solution provides more flexibility for toher return types. Both answers get +1 in my book though as they are both useful tidbits of info.
    – AaronLS
    Oct 24, 2011 at 21:46
  • 9
    @AaronLS To be fair, helpers don't return strings but IHtmlString, which take care of HTML encoding for you and protect your app from XSS attacks. Helpers also give you the convenience of Razor syntax in the helper itself, which you lose with functions. In other words, <p>Welcome, @username.</p> versus return new HtmlString("<p>Welcome, " + Html.Encode(username) + ".</p>");. Feb 21, 2012 at 5:14
  • 9
    using @helper in a single view doesn't make it available to other views, though. the reason I like @helper better is you can put html between your curly braces. @functions doesn't (easily) let you do that.
    – jfren484
    Oct 23, 2013 at 15:11
  • 5
    Just for the record: both @helper and @functions can be shared among many views, and both can be declared into and used by a single view (and I have personally found use for them in both shared/single scenarios). IMHO the only practical difference between them is the fact that a view helper adds syntactic sugar for returning rendered HTML snippets (or, more appropriate, HelperResult instances), while a view function is usually only useful for returning simple reference or value types.
    – rsenna
    Jan 24, 2014 at 17:48
309

You can use the @helper Razor directive:

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

Then you invoke it like this:

@WelcomeMessage("John Smith")
9
  • 14
    You can't put tags inside the @functions methods, so I like this answer.
    – jfren484
    Oct 23, 2013 at 15:11
  • 1
    Yes this is much better than declaring a function. Much more straight forward.
    – muglio
    Jun 5, 2015 at 6:37
  • 2
    But you can't return variables (hence the word function)
    – Paul
    Jun 16, 2016 at 18:02
  • 4
    Does asp.net core also support the @helper ?
    – MuM6oJuM6o
    Aug 13, 2018 at 18:38
  • 3
    @MuM6oJuM6o no it doesn't. You can find alternatives listed in this article What Happened To Helper In ASP.NET Core? Mar 12, 2020 at 14:16
29

If your method doesn't have to return html and has to do something else then you can use a lambda instead of helper method in Razor

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";

    Func<int,int,int> Sum = (a, b) => a + b;
}

<h2>Index</h2>

@Sum(3,4)
1
  • It is useful though if you need to access page's global variables in your function, is there an other way to do so ? :/ Feb 16, 2019 at 12:07
9

Take a look at Declarative Razor Helpers

0
7

In ASP.NET Core Razor Pages, you can combine C# and HTML in the function:

@model PagerModel
@{
}

@functions 
{
    void PagerNumber(int pageNumber, int currentPage)
    {
        if (pageNumber == currentPage)
        {
            <span class="page-number-current">@pageNumber</span>
        }
        else
        {
            <a class="page-number-other" href="/table/@pageNumber">@pageNumber</a>
        }
    }
}

<p>@PagerNumber(1,2) @PagerNumber(2,2) @PagerNumber(3,2)</p>
2

If you want to access your page's global variables, you can do so:

@{
    ViewData["Title"] = "Home Page";

    var LoadingButtons = Model.ToDictionary(person => person, person => false);

    string GetLoadingState (string person) => LoadingButtons[person] ? "is-loading" : string.Empty;
}
1
  • Since C# 7.0 this is the only proper and correct answer. GetLoadingState() here is local function. Apr 26, 2020 at 21:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.