第二會產生:
<li>
<span class="l"></span>
<span class="r"></span>
<a class="t" href="/Home/Contact">Contact</a>
</li>
比你這或許可以解釋的格式問題放在第一位有什麼不同:
<li>
<a href="../Home/Contact" class="active">
<span class="l"></span>
<span class="r"></span>
<span class="t">Nous contacter</span>
</a>
</li>
與HTML輔助,如HTML的問題。 ActionLink和RouteLink是他們總是用Html編碼文本,所以你不能使用HTML作爲文本。所以,一種可能性是:
<li>
<a href="@Url.RouteUrl("Contact", new { controller = "home", action = "contact" })" class="active">
<span class="l"></span>
<span class="r"></span>
<span class="t">Nous contacter</span>
</a>
</li>
如果你有很多的產生的另一種可能性是寫一個自定義HTML助手會爲你做的工作:
public static class HtmlExtensions
{
public static IHtmlString MyLink(
this HtmlHelper htmlHelper,
string linkText,
string routeName,
object routeValues
)
{
var spans = string.Format(
"<span class=\"l\"></span><span class=\"r\"></span><span class=\"t\">{0}</span>",
htmlHelper.Encode(linkText)
);
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var url = urlHelper.RouteUrl(routeName, routeValues);
var anchor = new TagBuilder("a");
var rvd = new RouteValueDictionary(routeValues);
var rd = htmlHelper.ViewContext.RouteData;
var currentAction = rd.GetRequiredString("action");
var currentController = rd.GetRequiredString("controller");
var controller = rvd["controller"] as string;
var action = rvd["action"] as string;
if (string.Equals(controller, currentController, StringComparison.OrdinalIgnoreCase) &&
string.Equals(action, currentAction, StringComparison.OrdinalIgnoreCase))
{
anchor.AddCssClass("active");
}
anchor.Attributes["href"] = url;
anchor.InnerHtml = spans;
return new HtmlString(anchor.ToString());
}
}
,然後:
<li>
@Html.MyLink("Nous contacter", "Contact", new { controller = "home", action = "contact" })
</li>
工程就像一個魅力。這是一個完整而詳盡的解決方案。太感謝了! – Mathieu 2012-01-15 14:55:21