我有一个可以这样调用的助手,没有问题:

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<TRN.DAL.Post>>' 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)
{
    <li>
        @Html.ActionLink(Helpers.Truncate(post.Content, 100), "Topic", new { TopicID = post.TopicID }, null)
        <p>By @Html.ActionLink(post.Username, "Members", new { MemberID = post.MemberID }, null) on @post.CreatedOn</p>
    </li>
}


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

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

最佳答案

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

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) ...

关于c# - MVC Razor:html.actionlink中的帮助程序结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20683941/

10-11 04:37