我如何定义一个方法在剃刀?
当前回答
Razor只是一个模板引擎。
您应该创建一个常规类。
如果你想在Razor页面中创建一个方法,把它们放在@functions块中。
其他回答
在razor中定义一个函数非常简单。
@functions {
public static HtmlString OrderedList(IEnumerable<string> items)
{ }
}
你可以在任何地方调用函数。就像
@Functions.OrderedList(new[] { "Blue", "Red", "Green" })
但是,同样的工作也可以通过helper完成。举个例子
@helper OrderedList(IEnumerable<string> items){
<ol>
@foreach(var item in items){
<li>@item</li>
}
</ol>
}
So what is the difference?? According to this previous post both @helpers and @functions do share one thing in common - they make code reuse a possibility within Web Pages. They also share another thing in common - they look the same at first glance, which is what might cause a bit of confusion about their roles. However, they are not the same. In essence, a helper is a reusable snippet of Razor sytnax exposed as a method, and is intended for rendering HTML to the browser, whereas a function is static utility method that can be called from anywhere within your Web Pages application. The return type for a helper is always HelperResult, whereas the return type for a function is whatever you want it to be.
Razor只是一个模板引擎。
您应该创建一个常规类。
如果你想在Razor页面中创建一个方法,把它们放在@functions块中。
你也可以使用@{}块来创建函数:
@{
async Task<string> MyAsyncString(string input)
{
return Task.FromResult(input);
}
}
然后在你的剃须刀页后面:
<div>@(await MyAsyncString("weee").ConfigureAwait(false))</div>
先不讨论什么时候(如果有的话)应该做这件事,@functions就是你做这件事的方式。
@functions {
// Add code here.
}
MyModelVm.cs
public class MyModelVm
{
public HttpStatusCode StatusCode { get; set; }
}
Index.cshtml
@model MyNamespace.MyModelVm
@functions
{
string GetErrorMessage()
{
var isNotFound = Model.StatusCode == HttpStatusCode.NotFound;
string errorMessage;
if (isNotFound)
{
errorMessage = Resources.NotFoundMessage;
}
else
{
errorMessage = Resources.GeneralErrorMessage
}
return errorMessage;
}
}
<div>
@GetErrorMessage()
</div>
您也可以使用下面的代码块。它更干净,功能更丰富。你也可以在上面插入变量,在下面插入函数。而不是使用2个单独的代码块。
@{
string exampleVariable = "just an example variable";
string anotherExampleVariable = "just another example variable";
string GetErrorMessage()
{
var isNotFound = Model.StatusCode == HttpStatusCode.NotFound;
string errorMessage;
if (isNotFound)
{
errorMessage = Resources.NotFoundMessage;
}
else
{
errorMessage = Resources.GeneralErrorMessage
}
return errorMessage;
}
}
推荐文章
- asp.net MVC中的@RenderSection是什么
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- 在哪里放置AutoMapper.CreateMaps?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 我如何提高ASP。NET MVC应用程序性能?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因