2012-01-27 38 views
1

我想在我的資源文件中包含 @ Html.ActionLink() 命令,但在調用資源時無法正確顯示它們。基本上是一個資源條目是這樣的:@ActionLink()在資源文件?

<div>Click here to @Html.ActionLink("contact us", null)</div> 

顯示爲

Click here to @Html.ActionLink("contact us", null) 

,而不是

Click here to contact us 

在我看來。有沒有辦法讓剃鬚刀標籤正確讀取?

回答

4

我不認爲你可以在資源文件中嵌入實際的代碼,並期望視圖引擎在渲染時調用它,它可能認爲它只是一個字符串(它不應該考慮任何超過那)。

更好的方法是使用string.Format

存儲作爲資源:

<div>Click here to {0}</div> 

然後在視圖(我是你的使用刀片猜測):

@string.Format(Resources.Global.LinkHtmlFormat, Html.ActionLink("contact us", null)) 

如果你這樣做了很多,你也可以「變甜它」使用自定義HTML幫助:

public static MvcHtmlString ResourceBasedActionLink(this HtmlHelper htmlHelper, string resourceName, string linkText, string actionName, string controllerName, object htmlAttributes) 
{ 
    var link = htmlhelper.ActionLink(linkText, actionName, controllerName, htmlAttributes); 
    return MvcHtmlString.Create(string.Format(resourceName, link))); 
} 

然後:

@Html.ResourceBasedActionLink(Resources.Global.LinkHtmlFormat, "Contact Us", "Contact", Controller", null) 
+1

絕妙的主意。而且我可以爲某些經常使用的鏈接定義標籤,並讓它們在助手中自動​​替換,所以每次調用方法時都不依賴於傳遞參數。非常感謝! – 2012-01-27 01:44:38

+0

ps。 @ string.Format(...)應該被封裝在@ Html.Raw(...)中以防止字符轉義(按照:http://stackoverflow.com/questions/14707484/how-to-escape- HTML的ActionLink的-AA-標籤 - 在字符串格式) – JohnLBevan 2013-03-02 01:49:42