How to create a function in a cshtml template?

2019-01-16 00:34发布

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.

5条回答
太酷不给撩
2楼-- · 2019-01-16 01:04

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)
查看更多
\"骚年 ilove
3楼-- · 2019-01-16 01:04

Use

 @functions{

private string GetUrl(string destination)
{}

Then you can call the function like-

查看更多
再贱就再见
4楼-- · 2019-01-16 01:06

You can use the @helper Razor directive:

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

Then you invoke it like this:

@WelcomeMessage("John Smith")
查看更多
贼婆χ
5楼-- · 2019-01-16 01:13

why not just declare that function inside the cshtml file?

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

<h2>index</h2>
@GetSomeString()
查看更多
【Aperson】
6楼-- · 2019-01-16 01:25
登录 后发表回答