Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC passing an ID in an ActionLink to the controller

Tags:

c#

asp.net-mvc

I can't seem to retrieve an ID I'm sending in a html.ActionLink in my controller, here is what I'm trying to do

<li>     <%= Html.ActionLink("Modify Villa", "Modify", "Villa", new { @id = "1" })%></li>       public ActionResult Modify(string ID)     {          ViewData["Title"] =ID;         return View();     } 

That's what a tutorial I followed recommended, but it's not working, it's also putting ?Length=5 at the end of the URL!

Here is the route I'm using, it's default

        routes.MapRoute(             "Default",                                              // Route name             "{controller}/{action}/{id}",                           // URL with parameters             new { controller = "Home", action = "Index", id = "" }  // Parameter defaults         ); 
like image 268
Tablet Avatar asked Nov 25 '08 10:11

Tablet


People also ask

How do I pass an object in ActionLink?

If you need to pass through the reference to an object that is stored on the server, then try setting a parameter of the link to give a reference to the object stored on the server, that can then be retrieved by the action (example, the Id of the menuItem in question).

What is the use of ActionLink in MVC?

ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.

How do I post on ActionLink?

ActionLink is rendered as an HTML Anchor Tag (HyperLink) and hence it produces a GET request to the Controller's Action method which cannot be used to submit (post) Form in ASP.Net MVC 5 Razor. Hence in order to submit (post) Form using @Html. ActionLink, a jQuery Click event handler is assigned and when the @Html.

What is difference between HTML ActionLink and URL action?

Yes, there is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.


1 Answers

Doesn't look like you are using the correct overload of ActionLink. Try this:-

<%=Html.ActionLink("Modify Villa", "Modify", new {id = "1"})%> 

This assumes your view is under the /Views/Villa folder. If not then I suspect you need:-

<%=Html.ActionLink("Modify Villa", "Modify", "Villa", new {id = "1"}, null)%> 
like image 80
AnthonyWJones Avatar answered Oct 08 '22 20:10

AnthonyWJones