Reputation: 446
I'm using MvcContrib's strongly typed RedirectToAction() to redirect from one controller action to another, while avoiding magic strings in my application flow, like so:
this.RedirectToAction<FooController>(c => c.Bar());
which in turn redirects to
/foo/bar/
... but now I'd like to be able to redirect to an URL with an anchor/hashtag at the end, and scroll the window to the <a name="yarrr" />
tag, like so:
/foo/bar/#yarrr
I could put the hashtag in TempData[], write it in a javascript variable and have the window scroll via javascript - but I'd rather follow convention and have the hashtag as the end of my URL.
Any ideas or home made solutions for this? MvcContrib doesn't seem to support it.
Upvotes: 2
Views: 1631
Reputation: 1038810
I am not aware of the existence of such an ActionLink overload in MvcContrib but writing one would be trivial:
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)
);
}
}
and then in your view:
@(Html.ActionLink<FooController>(c => c.Bar(), "click me", null, "yarrr"))
UPDATE:
Apparently I misunderstood your question as you were looking for a RedirectToAction
method in the controller, not inside the view. My answer is the same as previously: 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
)
);
}
}
and then inside your controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return this.RedirectToAction<FooController>(c => c.Bar(), "yarrr");
}
}
Upvotes: 5