Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to include a fragment identifier when using Asp.Net MVC ActionLink, RedirectToAction, etc.?

Tags:

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?

like image 461
Ricky Avatar asked Aug 08 '08 03:08

Ricky


People also ask

What is the use of ActionLink in MVC?

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.

What is the usage of a RedirectToAction?

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.

How do I post on ActionLink?

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.


1 Answers

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.

like image 90
LorenzCK Avatar answered Sep 20 '22 17:09

LorenzCK