问题
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) {}
回答1:
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.
回答2:
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>
来源:https://stackoverflow.com/questions/15095689/pass-object-through-html-actionlink-with-click