[英]T4MVC Links for SEO
我正在嘗試將我們的鏈接切換到T4MVC ,並且我的參數不是動作簽名的一個小問題。 我們有一條類似這樣的路線:
http://www.mydomain.com/{fooKey}/{barKey}/{barID}
==>導致BarController.Details(barID) 。
fooKey和barKey僅添加到鏈接以用於SEO目的。 (因為bar是foo的子實體,我們想在URL中表示該層次結構)
到目前為止,我們會使用
<% =Html.ActionLink(bar.Name, "Details", "Bar", new {barID = bar.ID, fooKey = bar.Foo.Key, barKey = bar.Key}, null)%>
這將導致我們使用BarController.Details(barID),同時在URL中保留fooKey和barKey。
現在我們開始使用T4MVC,我們嘗試將其更改為
<% =Html.ActionLink(bar.Name, MVC.Bar.Details(bar.ID), null)%>
由於barKey和fooKey不是Details操作簽名的一部分,因此URL中不再顯示它們。
有沒有辦法繞過這個而不必將這些參數添加到動作簽名中?
類似的事情也出現在T4MVC論壇上( 這個主題 )。 我想我會繼續在T4MVC中添加對它的支持。
實際上,我只想到了解決這個問題的有趣方法。 添加重載以傳遞額外參數的問題在於,您需要向采用ActionResult的所有其他T4MVC擴展方法添加類似的重載,這可能會變得混亂。
相反,我們可以使用流暢的方法,只需很少的努力就可以在任何地方使用它。 這個想法是你會寫:
<%= Html.ActionLink(
bar.Name,
MVC.Bar.Details(bar.ID)
.AddRouteValues(new {fooKey = bar.Foo.Key, barKey = bar.Key}))%>
或者,如果您只需要添加一個值:
<%= Html.ActionLink(
bar.Name,
MVC.Bar.Details(bar.ID)
.AddRouteValue("fooKey", bar.Foo.Key))%>
以下是AddRouteValues的實現方式:
public static ActionResult AddRouteValues(this ActionResult result, object routeValues) {
return result.AddRouteValues(new RouteValueDictionary(routeValues));
}
public static ActionResult AddRouteValues(this ActionResult result, RouteValueDictionary routeValues) {
RouteValueDictionary currentRouteValues = result.GetRouteValueDictionary();
// Add all the extra values
foreach (var pair in routeValues) {
currentRouteValues.Add(pair.Key, pair.Value);
}
return result;
}
public static ActionResult AddRouteValue(this ActionResult result, string name, object value) {
RouteValueDictionary routeValues = result.GetRouteValueDictionary();
routeValues.Add(name, value);
return result;
}
如果你能嘗試一下這將是很好的,讓我知道這對你有什么用。
謝謝,大衛
查看T4MVC.cs中生成的代碼。 有一些帶有ActionLink的html助手擴展。 您將不得不編寫一個帶有另一組路由值的重載,並將它們與ActionResult.GetRouteValueDictionary()組合在一起。
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, ActionResult result, IDictionary<string, object> htmlAttributes) {
return htmlHelper.RouteLink(linkText, result.GetRouteValueDictionary(), htmlAttributes);
}
謝謝jfar!
這是我使用的代碼,以防任何人需要它。 它可以使用重構工作,但它的工作原理
public static MvcHtmlString ActionLink<T>(this HtmlHelper<T> htmlHelper, string linkText, ActionResult result,
object extraRouteValues, object htmlAttributes)
{
RouteValueDictionary completeRouteValues = result.GetRouteValueDictionary();
RouteValueDictionary extraRouteValueDictionary = new RouteValueDictionary(extraRouteValues);
foreach (KeyValuePair<string, object> foo in extraRouteValueDictionary)
{
completeRouteValues.Add(foo.Key, foo.Value);
}
Dictionary<string, object> htmlAttributesDictionary = htmlAttributes != null ? htmlAttributes.GetType().GetProperties().ToDictionary(p => p.Name, p => p.GetValue(htmlAttributes, null)) : null;
return htmlHelper.RouteLink(linkText, completeRouteValues, htmlAttributesDictionary);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.