How to create a function in a cshtml template?
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.
You can use the @helper Razor directive:
@helper WelcomeMessage(string username)
{
<p>Welcome, @username.</p>
}
Then you invoke it like this:
@WelcomeMessage("John Smith")
为什么不直接在cshtml文件中声明该函数?
@functions{
public string GetSomeString(){
return string.Empty;
}
}
<h2>index</h2>
@GetSomeString()
如果你的方法不必返回html并且必须做其他的事情,那么你可以在Razor中使用lambda而不是helper方法
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
Func<int,int,int> Sum = (a, b) => a + b;
}
<h2>Index</h2>
@Sum(3,4)
链接地址: http://www.djcxy.com/p/85290.html
上一篇: 为什么在升级到新版本的Xcode后,安装Alcatraz的Xcode插件(如clang格式)不再有效?
下一篇: 如何在cshtml模板中创建一个函数?