Search code examples
asp.net-mvcviewactionlink

MVC Action Link in partial view


I'm new to MVC, trying to work out how @Html.ActionLinks work in partial views.

Background- here's the relevant portion of the solution

Models
  PersonViewModel.cs
Views
  Addresses
    AddressListPartial.cshmtl
  Person
    Details.cshtml

I created a PersonViewModel, which has FirstName, LastName and List of Addresses. I created a partial view using the List scaffold for the Address table, and added the following to my view for the Person to show the list of address on the Person/Details page:

@Html.Partial("~/Views/Address/AddressListPartial.cshtml", Model.Addresses)

This is correctly showing the AddressList on the page, however, the "Create", "Edit", etc links on the AddressList are linking to Views/Person/Edit/{id} instead of to Views/Address/Edit/{id}.

Partial view action link:

@Html.ActionLink("Edit", "Edit", new { id=item.AddressID }) |

So, the partial view is inheriting the ActionLink folder of the Person instead of the Address. Is there a way to make these ActionLinks in the partial view refer to the Address folder/controller instead of Person?

I tried this, but if the partial view is somewhere other than in a subfolder in the Views folder, this won't work:

@Html.ActionLink("Edit", "../Address/Edit", new { id=item.AddressID }) |

Solution

  • When you load the page, are you loading a Person from the PersonsController perhaps? I don't think the ActionLink really cares what partial view it's in, but rather what controller action rendered the view. And the default convention for resolving the URL when rendering the page would go back to that same controller.

    You can override that default and explicitly specify a controller using one of the overloads for ActionLink:

    @Html.ActionLink("Edit", "Edit", "Address", new { id = item.AddressID }, null)
    

    (Note that there's also an extra null parameter on the end. That particular overload also includes an object for HTML attributes. You're not using those, but there's no overload of this kind without it so you can just pass null to it.)