1

I have this routes:

routes.MapRoute(
                "Default",
                "user/{userId}/{controller}/{action}",
                new {controller = "Home", action = "Index" }
                );

            routes.MapRoute(
                "Short",
                "{controller}/{action}",
                new { controller = "Home", action = "Index"}
                );

My current location in browser:

http://my_site/user/197/UserEvents

On this page there are links:

@Html.ActionLink("Friends", "Index", "Friends")
@Html.ActionLink("Information", "Index", "UserInfo", new { userId = (string)null },null)

MVC re-use query parameters , so the first generated link:

my_site/user/197/Friends

The second link is generated:

my_site/UserInfo?userId=197

Why userId in the second link has a value of 197? Why not have a link:

my_site/UserInfo

2 Answers 2

1

I cannot pinpoint the exact location where MVC decides to reuse whatever route values it has at hand, but here's what I use in my projects:

//
// This fixes "ambient values" problem:
// http://stackoverflow.com/questions/2651675/asp-net-mvc-html-actionlink-maintains-route-values
// http://stackoverflow.com/questions/780643/asp-net-mvc-html-actionlink-keeping-route-value-i-dont-want
return new UrlHelper(
    new RequestContext(
        HttpContext.Current, 
        new RouteData {
            Route = urlHelper.RequestContext.RouteData.Route,
            RouteHandler = urlHelper.RequestContext.RouteData.RouteHandler
        }), urlHelper.RouteCollection)
    .Action(actionName, controllerName, routeValuesWithArea);

The key here is that neither RouteData.DataTokens nor RouteData.Values aren't set, so there's nothing MVC can possibly reuse.

Sign up to request clarification or add additional context in comments.

1 Comment

Can i see how it is used to generate links?
0

I would probably do something like

http://foo.com/user/events/197

http://foo.com/user/events?userId=197

I find that the more I try to jive with ASP.NET routing conventions the more time I can send developing my app.

public class UserController : Controller
{
    public ActionResult Events(long userId)
    {
        //Do Something...
    }
}

public class FriendsController : Controller
{
    public ActionResult Index(long userId)
    {
        //Do Something...
    }
}

1 Comment

I think you do not understand the question

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.