我是 MVC 的新手,正在尝试了解 @Html.ActionLink
在部分 View 中的工作方式。
背景 - 这是解决方案的相关部分
Models
PersonViewModel.cs
Views
Addresses
AddressListPartial.cshmtl
Person
Details.cshtml
我创建了一个 PersonViewModel,它有 FirstName
、LastName
和 Address
列表。我使用 Address 表的 List 脚手架创建了一个局部 View ,并在我的 View 中添加了以下内容,以便在 Person/Details
页面上显示地址列表:
@Html.Partial("~/Views/Address/AddressListPartial.cshtml", Model.Addresses)
这在页面上正确显示了地址列表,但是,地址列表上的“创建”、“编辑”等链接链接到 Views/Person/Edit/{id}
而不是到 Views/Address/Edit/{id}
。
部分 View 操作链接:
@Html.ActionLink("Edit", "Edit", new { id=item.AddressID }) |
因此,部分 View 继承了 Person
的 ActionLink
文件夹,而不是 Address
。有没有办法让局部 View 中的这些 ActionLinks 引用 Address 文件夹/ Controller 而不是 Person?
我试过了,但是如果局部 View 不在 Views 文件夹的子文件夹中,这将不起作用:
@Html.ActionLink("Edit", "../Address/Edit", new { id=item.AddressID }) |
最佳答案
当您加载页面时,您是否从 PersonsController
加载了一个 Person
?我不认为 ActionLink
真正关心它在哪个局部 View 中,而是关心哪个 Controller 操作呈现 View 。呈现页面时解析 URL 的默认约定将返回到同一 Controller 。
您可以覆盖该默认值并使用 ActionLink
的重载之一显式指定 Controller :
@Html.ActionLink("Edit", "Edit", "Address", new { id = item.AddressID }, null)
(请注意,最后还有一个额外的 null
参数。那个特定的重载还包括一个 HTML 属性的对象。你没有使用那些,而是 there's no overload of this kind without it 所以你可以通过null
到它。)
关于asp.net-mvc - 部分 View 中的 MVC 操作链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24412217/