How to create a function in a cshtml template?

后端 未结 6 801
醉话见心
醉话见心 2020-12-02 04:06

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

相关标签:
6条回答
  • 2020-12-02 04:42

    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>
    
    0 讨论(0)
  • 2020-12-02 04:43

    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)
    
    0 讨论(0)
  • 2020-12-02 04:46

    Take a look at Declarative Razor Helpers

    0 讨论(0)
  • 2020-12-02 04:49

    why not just declare that function inside the cshtml file?

    @functions{
        public string GetSomeString(){
            return string.Empty;
        }
    }
    
    <h2>index</h2>
    @GetSomeString()
    
    0 讨论(0)
  • 2020-12-02 04:53

    You can use the @helper Razor directive:

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

    Then you invoke it like this:

    @WelcomeMessage("John Smith")
    
    0 讨论(0)
  • 2020-12-02 04:56

    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;
    }
    
    0 讨论(0)
提交回复
热议问题