0

Is there an easy way to override the links that MVC generates for me so that I can always tack on another value.

for example http://www.site.com/{controller}/{action} is always rendered as http://www.site.com/{controller}/{action}/bob where bob is unique per user and tacked on to the end of every link generated using @Html.ActionLink or @Url.ActionLink.

Do I need to override each method or is there somewhere else I can insert this logic?

1 Answer 1

1

It sounds more like you really want a customized URL routing scheme. This is what that "route values" parameter in most of the ActionLink overloads is for. You can supply values to that method which are used to populate values in your mapped routes. By default the single route has a value of "id" appended to it, so in your case you could do this:

@Html.ActionLink("link", "Home", "Index", new { id = "bob" })

and you would get a URL that looks like:

http://www.site.com/Home/Index/bob

If you need the id parameter to also be there, you can add arbitrary new elements to the Route map, in your Global.asax code-behind:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{user}/{id}", // URL with parameters
    new
    {
        controller = "Home",
        action = "Index",
        user = "guest",
        id = UrlParameter.Optional
    } // Parameter defaults
);

Now you could use any of the following:

@Html.ActionLink("link", "Home", "Index", new { id = 1 })
@Html.ActionLink("link", "Home", "Index", new { user = "bob" })
@Html.ActionLink("link", "Home", "Index", new { user = "bob", id = 1 })

And you would get, respectively:

http://www.site.com/Home/Index/guest/1
http://www.site.com/Home/Index/bob
http://www.site.com/Home/Index/bob/1

MVC routing is pretty powerful, but like most powerful things, also complex. This article gives you a good introduction. It's written for an old version of MVC but the basics are the same (just change [] to {} in the routes.)

Also, if you don't want to have to remember to add the user parameter to every call, you could create your own HtmlHelper or UrlHelper extension methods to do it for you:

public static MvcHtmlString MyActionLink ( this HtmlHelper html, string text, string action, string controller, IDictionary<string, object> attrs)
{
  var data = new { user = GetTheUser() };
  return html.ActionLink(text, action, controller, data, attrs)
}

(Add additional overloads as needed; just pass "null" for action, controller, data, etc. if you want to use the defaults.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.