我正在使用MvcContrib的强类型RedirectToAction()从一个控制器动作重定向到另一个控制器动作,同时避免在我的应用程序流中使用魔术字符串,如下所示:
this.RedirectToAction<FooController>(c => c.Bar());
反过来又重定向到
/foo/bar/
...但现在我希望能够重定向到末尾有锚/主题标签的网址,并将窗口滚动到<a name="yarrr" />
标记,如下所示:
/foo/bar/#yarrr
我可以将标签放在TempData []中,将其写入javascript变量并通过javascript滚动窗口 - 但我宁愿遵循惯例并将主题标签作为我的URL的结尾。
任何想法或自制的解决方案? MvcContrib似乎不支持它。
答案 0 :(得分:5)
我不知道MvcContrib中是否存在这样的ActionLink重载,但写一个会很简单:
using System;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
public static class HtmlExtensions
{
public static IHtmlString ActionLink<TController>(
this HtmlHelper html,
Expression<Action<TController>> action,
string linkText,
object htmlAttributes,
string fragment
) where TController : Controller
{
var routeValues = Microsoft.Web.Mvc.Internal.ExpressionHelper
.GetRouteValuesFromExpression(action);
return html.RouteLink(
linkText: linkText,
routeName: null,
protocol: null,
hostName: null,
fragment: fragment,
routeValues: routeValues,
htmlAttributes: new RouteValueDictionary(htmlAttributes)
);
}
}
然后在你看来:
@(Html.ActionLink<FooController>(c => c.Bar(), "click me", null, "yarrr"))
更新:
显然我误解了你的问题,因为你在控制器中寻找RedirectToAction
方法,而不是在视图中。我的回答与以前相同:I am not aware of the existence of such an RedirectToAction overload in MvcContrib but writing one would be trivial:
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
public static class HtmlExtensions
{
public static RedirectResult RedirectToAction<TController>(
this Controller controller,
Expression<Action<TController>> action,
string fragment
) where TController : Controller
{
var routeValues = Microsoft.Web.Mvc.Internal.ExpressionHelper
.GetRouteValuesFromExpression(action);
var urlHelper = new UrlHelper(controller.ControllerContext.RequestContext);
return new RedirectResult(
UrlHelper.GenerateUrl(
routeName: null,
actionName: null,
controllerName: null,
protocol: null,
hostName: null,
fragment: fragment,
routeValues: routeValues,
routeCollection: urlHelper.RouteCollection,
requestContext: controller.ControllerContext.RequestContext,
includeImplicitMvcValues: true
)
);
}
}
然后在你的控制器里面:
public class HomeController : Controller
{
public ActionResult Index()
{
return this.RedirectToAction<FooController>(c => c.Bar(), "yarrr");
}
}