asp.net-mvc 如何在 cshtml 模板中创建函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6531983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a function in a cshtml template?
提问by Saeed Neamati
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.
我需要创建一个仅在一个 cshtml 文件中才需要的函数。您可以将我的情况视为 ASP.NET 页面方法,它们是在页面中实现的最小 Web 服务,因为它们的范围仅限于一个页面。我知道 HTML 帮助程序(扩展方法),但我的函数只需要在一个 cshtml 文件中。我不知道如何在视图中创建函数签名。 注意:我正在使用 Razor 模板引擎。
回答by
why not just declare that function inside the cshtml file?
为什么不在 cshtml 文件中声明该函数?
@functions{
public string GetSomeString(){
return string.Empty;
}
}
<h2>index</h2>
@GetSomeString()
回答by Daniel Liuzzi
You can use the @helper Razor directive:
您可以使用@helper Razor 指令:
@helper WelcomeMessage(string username)
{
<p>Welcome, @username.</p>
}
Then you invoke it like this:
然后你像这样调用它:
@WelcomeMessage("John Smith")
回答by Muhammad Hasan Khan
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
如果您的方法不必返回 html 并且必须执行其他操作,那么您可以在 Razor 中使用 lambda 而不是辅助方法
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
Func<int,int,int> Sum = (a, b) => a + b;
}
<h2>Index</h2>
@Sum(3,4)
回答by archil
Take a look at Declarative Razor Helpers
看看声明式剃刀助手
回答by Alexandre Daubricourt
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;
}