![](/img/trans.png)
[英]How to declare a variable of type Html.ActionLink in Razor View
[英]How to declare a variable in mvc view with razor to have html atribute class
我想在 MVC 視圖中的文本中顯示一個帶有 2 個鏈接的文本! 文本鏈接從服務器端是動態的,在控制器中看起來像這樣:
Model.Message = "You have used up all your credits for this month (see your credit balance {FirstLink}). You can buy credits {SecondLink}";
鑒於我有這樣的事情
@{
var messageToShow = @Model.Message;
var newText = Html.ActionLink(Model.LinkText, Model.LinkAction, Model.LinkController, Model.LinkRouteValues).ToString();
var link = Html.ActionLink(Model.SecondLinkText, Model.SecondLinkAction, Model.SecondLinkController, Model.LinkRouteValues).ToString();
}
@if (!string.IsNullOrEmpty(Model.LinkText))
{
messageToShow = messageToShow.Replace("{FirstLink}", newText);
}
@if (!string.IsNullOrEmpty(Model.SecondLinkText))
{
messageToShow = messageToShow.Replace("{SecondLink}", link);
}[![enter image description here][1]][1]
@Html.Raw(messageToShow)
這是像它一樣工作,但我必須像這樣將類添加到它
@Html.ActionLink(Model.SecondLinkText, Model.SecondLinkAction, Model.SecondLinkController, Model.LinkRouteValues, new { @class = "link" })
添加 ,new{ @class = "link"} 時出現語法錯誤,因為 razor 引擎對關閉的 } 進行了錯誤的解釋。
你能幫忙或者提出更好的解決方案嗎?
謝謝
為了解決語法錯誤,您的視圖模型需要包含 html 屬性的屬性,或者
public IDictionary<string, object> LinkAttributeValues { get; set; }
如果LinkRouteValues
是RouteValueDictionary
,或者
public object LinkAttributeValues { get; set; }
如果LinkRouteValues
是 typeof object
然后你的代碼變成
Html.ActionLink(Model.SecondLinkText, Model.SecondLinkAction,
Model.SecondLinkController, Model.LinkRouteValues, Model.LinkAttributeValues)
請注意,您的@if (!string.IsNullOrEmpty(Model....))
代碼行都是毫無意義的,因為如果LinkText
或SecondLinkText
為null
或空字符串,則前面的Html.ActionLink(..)
代碼行會拋出異常。
一種選擇是簡單地使用
<span>You have used up all your credits for this month (see your credit balance</span>
@Html.ActionLink(Model.LinkText, Model.LinkAction, Model.LinkController, Model.LinkRouteValues, new { @class = "link" })
<span>). You can buy credits</span>
@Html.ActionLink(Model.SecondLinkText, Model.SecondLinkAction, Model.SecondLinkController, Model.LinkRouteValues, new { @class = "link" })
或者如果你想在控制器中設置消息文本,你可以有 2 個屬性,比如string Message
和string Message2
並使用<span>@Model.Message1</span>....
當您在代碼塊中時,不需要在 ActionLink 前添加“@”前綴。 刪除它,我確信語法錯誤會消失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.