using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using System.Web.Routing; namespace MusicMatch.Utility { //From http://stevescodingblog.co.uk/redirecting-to-action-with-an-anchor-asp-net-mvc/ public class RedirectToActionAnchor : RedirectToRouteResult { /// /// Gets or sets the action. /// public string Action { get; set; } /// /// Gets or sets the anchor. /// public string Anchor { get; set; } /// /// Gets or sets the controller. /// public string Controller { get; set; } /// /// Initializes a new instance of the class. /// /// The action. /// The anchor. /// The route values. public RedirectToActionAnchor(string action, string anchor, object routeValues) : this(action, null, anchor, routeValues) { } /// /// Initializes a new instance of the class. /// /// The action. /// The controller. /// The anchor. /// The route values. public RedirectToActionAnchor(string action, string controller, string anchor, object routeValues) : base(new RouteValueDictionary(routeValues)) { if (string.IsNullOrWhiteSpace(action)) throw new ArgumentNullException(action); this.Action = action; this.Anchor = anchor; this.Controller = controller; } /// /// Enables processing of the result of an action method by a custom type that inherits from the class. /// /// The context within which the result is executed. /// The parameter is null. public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); this.RouteValues["action"] = this.Action; if (!string.IsNullOrWhiteSpace(this.Controller)) this.RouteValues["controller"] = this.Controller; RequestContext requestContext = new RequestContext(context.HttpContext, RouteTable.Routes.GetRouteData(context.HttpContext)); VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(requestContext, RouteName, RouteValues); if (vpd == null || string.IsNullOrWhiteSpace(vpd.VirtualPath)) { throw new InvalidOperationException("No route matched"); } string target = vpd.VirtualPath; if (!string.IsNullOrWhiteSpace(this.Anchor)) { // Add the anchor onto the end: target += string.Format("#{0}", Anchor); } context.HttpContext.Response.Redirect(target, false); } } }