首页 > 解决方案 > MVC 区域中的 Html.ActionLink 是否可以在不使用 new { area = "" } 指定的情况下为默认/根区域呈现链接

问题描述

我遇到了这样一种情况,即在默认/根区域中有大量 Html.ActionLink 调用,这些调用未指定区域,如下例所示。

@Html.ActionLink("Home", "Index", "Home")

问题是我现在正在使用一个新的 MVC 区域,它正在从默认/根区域呈现部分视图,但链接没有被正确呈现,因为该区域没有被定义,如下例所示。

@Html.ActionLink("Home", "Index", "Home", new { area = "" })

显而易见的解决方案是将区域规范添加到所有 Html.ActionLink 调用中,但不幸的是它们的数量很大,而且要全部更改需要付出很大的努力。

我处于必须使用默认/根区域中的这些链接的情况,并且想知道是否有一种方法可以将某些内容设置为 Html.ActionLink 调用将首先搜索当前区域但如果没有匹配的控制器/视图是发现它会搜索默认/根区域?我想声明我在项目中有多个 MVC 区域,因此解决方案需要是一个不仅适用于包括默认/根目录的两个区域的解决方案。

标签: asp.net-mvcrazorhtml-helperasp.net-mvc-areas

解决方案


   1. Create a new ASP.NET MVC 3 application using the default Visual Studio template
   2. Add an area called Admin using Visual Studio designer by right clicking on the project
   3. Add new Controller in ~/Areas/Admin/Controllers/MeetsController:

        public class MeetsController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
    Add a corresponding view ~/Areas/Admin/Views/Meets/Index.cshtml

    In the layout (~/Views/Shared/_Layout.cshtml) add links:

    @Html.ActionLink("Admin", "Index", "Meets", new { area = "Admin" }, null)
    @Html.ActionLink("Admin", "Index", "Meets", new { area = "" }, null)
    Run the application.
    Rendered HTML for the anchors:

    <a href="/Admin/Meets">Admin</a>
    <a href="/Meets">Admin</a>
    As expected the first link works whereas the second doesn't.

我希望你对此有所了解...


推荐阅读