2013-12-19 46 views
1

我有一個幫手,我可以這樣調用沒有問題:MVC剃刀:助手導致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<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> 
    } 
} 
+0

ActionLink似乎沒有錯,但是你可以通過替換'Helpers.Truncate(post.Content,100)''例如''test「'來驗證ActionLink是否工作? – Marthijn

+0

@Marthijn這也可以: @ Html.ActionLink(「Test」,「Topic」,new {TopicID = post.TopicID},null) –

回答

1

我建議將輔助函數更改爲您選擇的類中的靜態函數。例如:

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

幾乎就在那裏。這個出來了: 'CS0127:因爲'System.Action '返回void,所以返回關鍵字不能跟着一個對象表達式' –

+0

我忘記了它對於輔助函數有點複雜返回一個值(見這篇文章:http://stackoverflow.com/questions/10451036/can-i-return-a-string-using-the-helper-syntax-in-razor)我建議你做一個靜態函數在這個函數的類中。生病更新我的帖子。 – Marthijn

+0

標記爲答案,因爲我已爲此項目採用此策略。 謝謝! –

4

試試這個:

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

解決了!儘管神祕的消息是因爲我的幫助者返回了helperresult,並且Actionlink中的第一個參數需要一個字符串。 –