Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my ActionLink is not working?

Tags:

c#

asp.net-mvc

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?

like image 235
gurehbgui Avatar asked May 29 '13 10:05

gurehbgui


2 Answers

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.

like image 149
Erik Schierboom Avatar answered Oct 20 '22 14:10

Erik Schierboom


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.

like image 20
CodeCaster Avatar answered Oct 20 '22 15:10

CodeCaster