MVC Razor: Helper result in html.actionlink

2019-06-05 01:51发布

问题:

I have a helper which I can call like this with no problem:

Helpers.Truncate(post.Content, 100);

However when I call it in a @Html.ActionLink I get the following Error:

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

This is the code affected:

@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>
}

My helper code is located in App_Code\Helpers.cshtml and the code is below:

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

回答1:

I suggest to change the helper function into a static function in a class of your choice. For example:

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

The in your view you use:

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

Optionally you can change this function into an extension of string, there are plenty examples on how to do that:

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


回答2:

Try this:

@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) + "...")
    }
}