Asp.net-Mvc

“區域”之間的 ASP.NET MVC Html.ActionLink

  • March 25, 2011

我在我的 MVC3 項目中添加了一個新區域,我正在嘗試從 _Layout 頁面連結到新區域。我添加了一個名為“Admin”的區域,其中包含一個控制器“Meets”。

我使用 Visual Studio 設計器添加區域,使其具有正確的區域註冊類等,並且 global.asax 文件正在註冊所有區域。

但是,當我在根目錄中的頁面中使用以下 2 個操作連結時,我遇到了一些問題:

@Html.ActionLink("Admin", "Index", "Meets", new { area = "Admin" }, null)
@Html.ActionLink("Admin", "Index", "Meets", new { area = "" }, null)

當點擊這兩個連結時,我被帶到管理區域的 Meets 控制器,然後應用程序繼續拋出一個錯誤,說它找不到索引頁面(即使索引頁面存在於區域子的 Views 文件夾中)目錄。

第一個連結的 href 如下所示:

http://localhost/BCC/Meets?area=Admin

第二個連結的 href 如下所示:

http://localhost/BCC/Meets

此外,如果我點擊我希望創建的連結:

http://localhost/BCC/Admin/Meets

我只是得到一個資源找不到錯誤。都非常令人費解!我希望有人能幫幫忙…

我發現了這一點 - 我創建了一個新的測試項目,並做了與我之前做的完全相同的事情並且它起作用了……然後在進一步檢查了兩個項目之間與路線相關的所有事情之後,我發現了一個差異。

在我的密件抄送應用程序的 global.asax 文件中,莫名其妙地出現了一行惡意程式碼:

       public static void RegisterRoutes(RouteCollection routes)
       {
           // Problem here
           routes.Clear();

           routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

           routes.MapRoute(
               "Default", // Route name
               "{controller}/{action}/{id}", // URL with parameters
               new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
           );
       }

       protected void Application_Start()
       {
           AreaRegistration.RegisterAllAreas();

           RegisterGlobalFilters(GlobalFilters.Filters);
           RegisterRoutes(RouteTable.Routes);
       }

正如您所看到的,我的評論在哪裡,有時我在 RegisterRoutes 的開頭放置了 routes.Clear() 呼叫,這意味著在我在 Application_Start 中註冊了區域之後,我立即清除了剛剛的內容掛號的。

感謝您的幫助……它最終導致了我的救贖!

確實很奇怪。對我來說效果很好的步驟:

  1. 使用預設的 Visual Studio 模板創建一個新的 ASP.NET MVC 3 應用程序
  2. Admin通過右鍵點擊項目添加一個名為使用 Visual Studio 設計器的區域
  3. 在以下位置添加新控制器~/Areas/Admin/Controllers/MeetsController
public class MeetsController : Controller
{
   public ActionResult Index()
   {
       return View();
   }
}
  1. 添加對應的視圖~/Areas/Admin/Views/Meets/Index.cshtml
  2. 在佈局 ( ~/Views/Shared/_Layout.cshtml) 添加連結:
@Html.ActionLink("Admin", "Index", "Meets", new { area = "Admin" }, null)
@Html.ActionLink("Admin", "Index", "Meets", new { area = "" }, null)
  1. 執行應用程序。

為錨點渲染 HTML:

<a href="/Admin/Meets">Admin</a>
<a href="/Meets">Admin</a>

正如預期的那樣,第一個連結有效,而第二個連結無效。

那麼你的設置有什麼不同呢?

引用自:https://stackoverflow.com/questions/5432185