I have a Controller Method like this:
public ActionResult Foo2(int uId)
{
return View();
}
now I added a action link to this:
@Html.ActionLink("Test", "Foo2", "Main", new { uId = 12 })
But the result when I click it is:
.../Main/Foo2?Length=8
Why this is not working?
You are using the wrong overload of the ActionLink
method. You should be using:
@Html.ActionLink("Test", "Foo2", "Home", new { uId = 12 }, null)
This overload will interpret the new { uId = 12 }
to be used as the route values, and not as the HTML attributes. The overload you are using does interpret the new { uId = 12 }
as the object with the TML attributes of the action link. By calling the overload specified above you pass in null
as the fifth parameter, which will now be used for the HTML attributes and your object as the route values.
We can easily see what is happening by looking at what gets rendered:
@Html.ActionLink("Test", "Foo2", "Home", new { uId = 12 })
// Renders: <a href="/Home/Foo2?Length=4" uId="12">Test</a>
@Html.ActionLink("Test", "Foo2", "Home", new { @class = "test-class" })
// Renders: <a class="test-class" href="/Home/Foo2?Length=4">Test</a>
@Html.ActionLink("Test", "Foo2", "Home", new { uId = 12 }, null)
// Renders: <a href="/Home/Foo2?uId=12">Test</a>
@Html.ActionLink("Test", "Foo2", "Home", new { uId = 12 }, new { @class = "test-class" })
// Renders: <a class="test-class" href="/Home/Foo2?uId=12">Test</a>
Hope this clears it up a bit.
MVC is calling the wrong overload, because it has a few methods with the same parameter count. Try this:
@Html.ActionLink("Test", "Foo2", "Main", new { uId = 12 }, null)
See also this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With