Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

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.

share|improve this answer
    
Can i see how it is used to generate links? –  DeeRain Aug 10 '11 at 10:10
add comment

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...
    }
}
share|improve this answer
    
I think you do not understand the question –  DeeRain Aug 10 '11 at 8:33
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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