How Can I Stop ASP.Net MVC Html.ActionLink From Using Existing Route Values?

前端 未结 3 1336
别那么骄傲
别那么骄傲 2020-12-13 21:36

The website I\'m working on has some fairly complicated routing structures and we\'re experiencing some difficulties working with the routing engine to build URLs the way we

相关标签:
3条回答
  • 2020-12-13 22:02

    Setting route values to be null or empty string when calling Html.ActionLink or Html.RouteLink (or any URL generation method) will clear out the "ambient" route values.

    For example, with the standard MVC controller/action/id route suppose you're on "Home/Index/123". If you call Html.RouteLink(new { id = 456 }) then MVC will notice the "ambient" route values of controller="Home" and action="Index". It will also notice the ambient route value of id="123" but that will get overwritten by the explicit "456". This will cause the generated URL to be "Home/Index/456".

    The ordering of the parameters matters as well. For example, say you called Html.RouteLink(new { action = "About" }). The "About" action would overwrite the current "Index" action, and the "id" parameter would get cleared out entirely! But why, you ask? Because once you invalidate a parameter segment then all parameter segments after it will get invalidated. In this case, "action" was invalidated by a new explicit value so the "id", which comes after it, and has no explicit value, also gets invalidated. Thus, the generated URL would be just "Home/About" (without an ID).

    In this same scenario if you called Html.RouteLink(new { action = "" }) then the generated URL would be just "Home" because you invalidated the "action" with an empty string, and then that caused the "id" to be invalidated as well because it came after the invalidated "action".

    0 讨论(0)
  • 2020-12-13 22:06

    Solution at the root of the problem

    It seems that the optimal solution (that doesn't smell like a workaround) is the one that solves the problem where it has roots and that's in routing.

    I've written a custom Route class called RouteWithExclusions that is able to define route value names that should be excluded/removed when generating URLs. The problem is when routing falls through routes table and subsequent routes don't have the same route value names...

    The whole problem is detailed and explained in my blog post and all the code is provided there as well. Check it out, it may help you solve this routing problem. I've also written two additional MapRoute extension methods that take an additional parameter.

    0 讨论(0)
  • 2020-12-13 22:07

    If you want total control of the link, just build the link yourself:

    <a href="~/variableA/variableB/<%= Html.Encode(Model.Target) %>">Click Here</a>
    

    Substitute whatever you need inside the href attribute.

    0 讨论(0)
提交回复
热议问题