8

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
gurehbgui
  • 14,236
  • 32
  • 106
  • 178

3 Answers3

6

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.

Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
5

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.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
0

According an other Stackoverflow Question you should try this order:

@Html.ActionLink("Test", "Foo2", "Main", new { uId = 12 }, null)
Community
  • 1
  • 1
Sir l33tname
  • 4,026
  • 6
  • 38
  • 49