请注意,@functions 对应的是Razor的代码段,需要添加{},并且functions内部是正规的c#方法。
如果要在多个页面同时使用这个functions,可以将这个方法移植到app_code中,假定文件名为UIHelper.cshtml。并且里面的方法必须定义为静态的。这个很好理解,UIHelper相当于类名,而其中的functions就相当于方法,如果要通过类名.方法名来进行调用,则必须将方法定义成静态的。
UIHelper.cshtml文件代码
@helper ShowUnit(int count)
{
if (count == 0)
{
@:免费
}
else
{
@count
}
}
@functions {
public static IHtmlString Check(int count)
{
string result = "";
if (count == 0)
{
result = "fsdfsdfsdfd";
}
else
{
result = count.ToString();
}
return new HtmlString(result);
}
}
//自定义函数@functions
@functions{
public static IHtmlString Get(int count)
{
string result = "";
if (count == 0)
{
result = "不存在";
}
else
{
result = "存在";
}
return new HtmlString(result);
}
}
总结:helper针对的是直接输出html内容并且具有简单的逻辑的情况,并且helper没有任何返回值,而functions自定义函数则要强大很多,如果functions需要返回html内容,那么返回值是IHtmlString类型,如果不需要返回值,则可以设置为void,但是如果没有返回值也就失去了定义function的意义,所以一般返回值均为IHtmlString。对于View层的重构,我们可以采用helper和自定义函数functions的方式来实现。
补充:当在页面中引入新类型的时候,可能命名空间很长,导致页面间好多重复代码,可以在view页面的开始位置导入命名空间,
如下:@model IEnumrable<MVC.Test.Animal>可以改为
@using MVC.Test
@model IEnumrable<Animal>;
当所有view页面都会引入相同的命名空间的时候,可以采取一种方式避免每个页面都要用@using来引入,在Views目录下有web.config文档,可以在此文档下的
<system.web.webPages.razor>区段加入每个页面都会用到的命名空间,如下:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Routing" />
<add namespace="WebApplication1" />
</namespaces>
</pages>
</system.web.webPages.razor>








