【问题标题】:MVC Razor: Helper result in html.actionlinkMVC Razor:Helper 结果在 html.actionlink
【发布时间】:2013-12-19 14:13:40
【问题描述】:

我有一个助手,我可以毫无问题地这样调用它:

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

【问题讨论】:

  • ActionLink 似乎没有任何问题,但是您能否通过将Helpers.Truncate(post.Content, 100) 替换为例如"test" 来验证ActionLink 是否有效?
  • @Marthijn 这也有效:@Html.ActionLink("Test", "Topic", new { TopicID = post.TopicID }, null)

标签: c# asp.net-mvc razor


【解决方案1】:

试试这个:

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

【讨论】:

  • 解决了!尽管有神秘的消息,这是因为我的助手返回了 helperresult 并且 Actionlink 中的第一个参数需要一个字符串。
【解决方案2】:

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

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

【讨论】:

  • 快到了。随之而来的是:CS0127: Since 'System.Action&lt;System.IO.TextWriter&gt;' returns void, a return keyword must not be followed by an object expression
  • 我忘了帮助函数返回值有点复杂(见这篇文章:stackoverflow.com/questions/10451036/…)我建议你在一个类中为这个函数创建一个静态函数。我会更新我的帖子。
  • 标记为答案,因为我已经为我的项目采用了这个策略。谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多