I want some links to include a fragment identifier. Like some of the URLs on this site:
Debugging: IE6 + SSL + AJAX + post form = 404 error#5626
Is there a way to do this with any of the built-in methods in MVC? Or would I have to roll my own HTML helpers?
ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.
The RedirectToAction() Method This method is used to redirect to specified action instead of rendering the HTML. In this case, the browser receives the redirect notification and make a new request for the specified action. This acts just like as Response.
ActionLink is rendered as an HTML Anchor Tag (HyperLink) and hence it produces a GET request to the Controller's Action method which cannot be used to submit (post) Form in ASP.Net MVC 5 Razor. Hence in order to submit (post) Form using @Html. ActionLink, a jQuery Click event handler is assigned and when the @Html.
As Brad Wilson wrote, you can build your own link in your views by simply concatenating strings. But to append a fragment name to a redirect generated via RedirectToAction (or similar) you'll need something like this:
public class RedirectToRouteResultEx : RedirectToRouteResult { public RedirectToRouteResultEx(RouteValueDictionary values) : base(values) { } public RedirectToRouteResultEx(string routeName, RouteValueDictionary values) : base(routeName, values) { } public override void ExecuteResult(ControllerContext context) { var destination = new StringBuilder(); var helper = new UrlHelper(context.RequestContext); destination.Append(helper.RouteUrl(RouteName, RouteValues)); //Add href fragment if set if (!string.IsNullOrEmpty(Fragment)) { destination.AppendFormat("#{0}", Fragment); } context.HttpContext.Response.Redirect(destination.ToString(), false); } public string Fragment { get; set; } } public static class RedirectToRouteResultExtensions { public static RedirectToRouteResultEx AddFragment(this RedirectToRouteResult result, string fragment) { return new RedirectToRouteResultEx(result.RouteName, result.RouteValues) { Fragment = fragment }; } }
And then, in your controller, you'd call:
return RedirectToAction("MyAction", "MyController") .AddFragment("fragment-name");
That should generate the URL correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With