2011-06-08 74 views
1

我读了[useful article]这个说我可以创建一个内联助手的库,把它们放在特殊文件夹App_Code的视图中。当我将@helper函数移到那里时,呼叫扩展帮助程序我已停止工作。我读[in this SO article],有一个问题,因为@helper是静态的,但我的扩展不是......我尝试了2种不同的方式,但无法使其工作。它没有认识到我的推广助手的存在。从内联助手调用扩展助手 - 如何?

'System.Web.WebPages.Html.HtmlHelper' does not contain a definition for 'Image' 

我的扩展助手叫'图像'。我应该寻找什么?

+0

这将有助于看到你尝试过哪两种方式。你是否像这样使用了完整的助手路径:@ CustomHelpers.Truncate(ViewBag.Message,8)在这种情况下,你不需要使用CustomHelpers.cshtml文件的“使用”? – 2011-06-12 04:21:08

回答

0

好吧,我的问题曾与做叫它命名空间...所以我有在\ Views \ Shared \ HtmlHelpers.cs:

public static class Html 
{ 
    public static MvcHtmlString Image(this HtmlHelper helper, string src, object htmlAttrs = null) 
    { 

我通常从我的网页访问像这样:

@Html.Image("/path/to/image") 
在App_Code文件\ Helpers.cshtml

@helper AddButton(string path) 
{ 
    var Html = ((System.Web.Mvc.WebViewPage) WebPageContext.Current.Page).Html; 
    @Html.Image(path); 
} 

但智能感知强调有 “图像”,并抱怨:

'System.Web.Mvc.HtmlHelper<object>' does not contain a definition for 'Image' 
and no extension method 'Image' accepting a first argument of type 
'System.Web.Mvc.HtmlHelper<object>' could be found (are 
you missing a directive or an assembly reference?) 

的原因似乎是帮助者.cshtml需要有名称空间的@using ...在我的常规页面上,名称空间包含在我的web.config中,但此页面似乎不受此机制的限制

1

当你在剃刀视图中写Helperextension。 您需要将它称为FileName.Method。

如您有CustomHelpers.cshtml文件中的app_code和你有一个方法

 @helper TruncateString(string input, int length) 
    {   
     if (input.Length <= length) 
     {  
      @input   
     } 
     else 
     { 
      @input.Substring(0, length)<text>...</text>   
     } 
    } 

你可以从index.cshtml

@CustomHelpers.TruncateString("Example", 8); 
1

作为例子的问题,下面的代码使用“RenderPage”功能的助手库中:

@helper GetSection(string sectionName, string sectionTitle, string sectionFileName){ 
    <div id="@sectionName"> 
     <h1>@sectionTitle</h1> 
     @System.Web.WebPages.WebPageContext.Current.Page.RenderPage("~/Views/Shared/MySections/" + @sectionFileName) 
    </div> 
} 

它演示了如何获取“当前页面”(上下文)的实例。

此代码可以在位于您的项目的“* app_code *”子文件夹内的您自己的“公共库”剃刀帮手文件(“.cshtml”)内正常工作。