MVC Razor:Helper导致html.actionlink

我有一个帮手,我可以这样打电话没问题:

Helpers.Truncate(post.Content, 100); 

但是当我在@Html.ActionLink中调用它时,我得到以下错误:

 Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS1928: 'System.Web.Mvc.HtmlHelper<System.Collections.Generic.IEnumerable>' does not contain a definition for 'ActionLink' and the best extension method overload 'System.Web.Mvc.Html.LinkExtensions.ActionLink(System.Web.Mvc.HtmlHelper, string, string, object, object)' has some invalid arguments 

这是受影响的代码:

 @foreach (var post in Model) { 
  • @Html.ActionLink(Helpers.Truncate(post.Content, 100), "Topic", new { TopicID = post.TopicID }, null)

    By @Html.ActionLink(post.Username, "Members", new { MemberID = post.MemberID }, null) on @post.CreatedOn

  • }

    我的帮助程序代码位于App_Code \ Helpers.cshtml中,代码如下:

     @helper Truncate(string input, int length) { if (input.Length <= length) { @input } else { @input.Substring(0, length)... } } 

    我建议将辅助函数更改为您选择的类中的静态函数。 例如:

     public static string Truncate(string input, int length) { if (input.Length <= length) { return input; } else { return input.Substring(0, length) + "..."; } } 

    您在视图中使用:

     @Html.Actionlink(MyNamespace.MyClass.Truncate(input, 100), ... 

    您可以选择将此函数更改为string的扩展名,有很多示例说明如何执行此操作:

     public static string Truncate(this string input, int length) ... 

    试试这个:

     @Html.ActionLink(Truncate(post.Content, 100).ToString(), "Home") @helper Truncate(string input, int length) { if (input.Length <= length) { @Html.Raw(input) } else { @Html.Raw(input.Substring(0, length) + "...") } }