pass object through @Html.ActionLink with click

NNassar picture NNassar · Feb 26, 2013 · Viewed 11.3k times · Source

What I'm trying to do is pass the item that was clicked to the controller for editing but the only thing I can pass to the controller is a string.

view:

foreach (MenuItemViewModel menuitem in category.MenuItemList)
{
  <span class="MenuItemTitel">
     @if (IsAdmin)
     {
       <span class="AdminSpan">
          @Html.ActionLink("Edit", "EditPage", "Admin", new { name = menuitem.Title })
       </span>
     }
      @menuitem.Title
  </span> 
}

Controller:

public ActionResult EditPage(MenuItemViewModel MenuItem) {}

Answer

Yaakov Ellis picture Yaakov Ellis · Feb 26, 2013

The @Html.ActionLink() method will generate a url link to the given Controller/Action. Thus, it can only contain parameters that can be contained in the url of the link. So you cannot pass an object through on the url.

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).

Parameters in the ActionLink are set through the collection that you passed in as the third item in your function call above. Assuming default routing, this would give an address that looks like /Admin/EditPage/?name=XXX where XXX is the value of menuitem.Title. If you included something else here like itemId = menuitem.Id then it would add this as a query string parameter to the url generated, which would then be accessible to the action that is the target of this link.