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) {}
有帮助吗?

解决方案

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.

其他提示

I did pass the object with helpt @Html.Action(). See the code below:

@Html.ActionLink("Lista Valores", "Lista", "RandomName",
new {
    Id = @ViewBag.Id,
    Name = "fdsfsadf",
    LastName = @ViewBag.LastName,
    Breed = @ViewBag.Breed,
    System = ViewBag.sys
}, null)

Controller:

public ActionResult Lista(CharNames character)
{
    return View(character);
}

View:

<p>@Html.LabelFor(x => x.Id) @Model.Id</p>
<p>@Html.LabelFor(x => x.Name) @Model.Name</p>
<p>@Html.LabelFor(x => x.LastName) @Model.LastName</p>
<p>@Html.LabelFor(x => x.Breed) @Model.Breed</p>
<p>@Html.LabelFor(x => x.System) @Model.System</p>
on the Controller:
[Route("customer/detail")]
public ActionResult Detail(Customer customer)
{
   return View(customer);
}

on the source view:

@model List<AI.Models.Customer>
@{
   ViewBag.Title = "Customer List";
   Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Customers</h2>
<ul>
  @foreach (var customer in Model)
  {
    <li>@Html.ActionLink(@customer.Name, "detail", "customer", @customer, null)</li>
  }
</ul>

on the target view:
@model AI.Models.Customer
@{
  ViewBag.Title = "Details";
  Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Customer Name : @Model.Name</h2>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top