How to create a function in a cshtml template?

asp.net Mvcasp.net Mvc-3Razor

asp.net Mvc Problem Overview


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.

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

why not just declare that function inside the cshtml file?

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

<h2>index</h2>
@GetSomeString()

Solution 2 - asp.net Mvc

You can use the @helper Razor directive:

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

Then you invoke it like this:

@WelcomeMessage("John Smith")

Solution 3 - asp.net Mvc

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)

Solution 4 - asp.net Mvc

Solution 5 - asp.net Mvc

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>

Solution 6 - asp.net Mvc

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaeed NeamatiView Question on Stackoverflow
Solution 1 - asp.net Mvcuser156888View Answer on Stackoverflow
Solution 2 - asp.net MvcDaniel LiuzziView Answer on Stackoverflow
Solution 3 - asp.net MvcMuhammad Hasan KhanView Answer on Stackoverflow
Solution 4 - asp.net MvcarchilView Answer on Stackoverflow
Solution 5 - asp.net MvcPetr VoborníkView Answer on Stackoverflow
Solution 6 - asp.net MvcAlexandre DaubricourtView Answer on Stackoverflow