Question

I have seen an interesting behavior for asp .net "Url.Action".

A link like <a href="@Url.Action("Index", "Soru")" >@baslik</a> seems in client browser as <a href="/Soru/Index">denemebaslik</a>, then user clicks this link and goes to target page.

In this target page a link like <a href="@Url.Action("Index", "Soru")" >@baslik</a> seems in client browser as <a href="/Soru/Index/29271654-e19a-4096-8795-3283d8a208ed">denemebaslik</a>

@Url.Action behaves different in different pages. My route config is like

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{*id}",
            defaults: new { controller = "Giris", action = "Index", id = UrlParameter.Optional }
        );

Why is this beaviour so that?

Was it helpful?

Solution

MVC will pick up the parameters in the query string of the current page and include them when rendering a link to the same route, basically preserving the existing parameters.

If this is the scenario you're experiencing - it's by design. It means that, for situations where the action link points back to the page itself, the parameters are already there for you. For example, if you have "sort ascending/descending" links, the other parameters (e.g. price/description) continue to be included in the links without you having to encode them every time.

If you don't want the additional parameters, specify the parameter with an Empty string, like this

<a href="@Url.Action("Index", "Soru", new { id = "" })">@baslik</a>

Note that you cannot assign null to the parameter because it is an anonymous type. Empty strings work just fine.

Incidentally, I'm sure you know this, but you can also use the more convenient @Html.ActionLink too:

@Html.ActionLink(baslik, "Index", "Soru", new { id = "" })">

Hope this helps you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top