我有一个返回 ActionResult 的扩展方法(为演示目的而简化):
public static ActionResult GetTestActionResult(this HtmlHelper htmlHelper, int productId)
{
return MVC.Products.Details(productId);
}
我在 Html.ActionLink 中使用它:
@Html.ActionLink("Product Details", Html.GetTestActionResult(Model.ProductId), new { @class = "button blue" });
我正在为选项卡使用自定义 jQuery 插件,它使用这些哈希片段进行导航。我想通过将哈希片段标记到 URL 的末尾来添加要打开的选项卡。
Html.ActionLink 确实有片段的重载,即:
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
string protocol,
string hostName,
string fragment,
Object routeValues,
Object htmlAttributes
)
然而,这充满了令人讨厌的魔法字符串,T4MVC 旨在删除这些字符串。无论如何在我的静态扩展方法(GetTestActionResult)中将片段添加到路由字典中?
就像是:
return MVC.Products.Details(productId).AddRouteValue(String.Empty, "#tab-similar-products");
我知道关于 SO 有两个类似的问题和答案,但它们并不能完全为我提供我正在寻找的东西。在将片段传递回视图之前,我需要将片段包装到 ActionResult 中:
更新:
使用下面 David Ebbo 的修复程序,我进行了以下更改。有点hacky,但它有效:
首先,我更改了返回 ActionResult 的内部函数,以便它还将片段添加为路由值(不理想但有效):
return MVC.Products.Details(productId).AddRouteValue("tab", "#tab-similar-products");
然后在视图中,它将该片段值从路由字典中复制出来,然后删除该路由值以确保完整性。
// get my ActionResult with the tab fragment tagged on as a route value
var actionResult = Html.GetTestActionResult(item.Key, Model.ClaimId);
// get the tab fragment value
var tabRoute = actionResult.GetRouteValueDictionary().FirstOrDefault(r => r.Key == "tab").Value ?? "none";
// remove the route value, otherwise it will get tagged to the querystring
actionResult.GetRouteValueDictionary().Remove("tab");
// display
@Html.ActionLink("Product Details", Html.GetTestActionResult(Model.ProductId), new { @class = "button blue" }, fragment: tabRoute.ToString());
我确信有一种更漂亮的方法可以用 ActionResult 返回片段,但目前这可行。谢谢大卫。