2011-03-09 81 views
36

是否有人知道如何在ASP.NET MVC3中配置區域? 我閱讀了一篇關於here中的地區的文章。 但該文章不基於MVC3。 在MVC3沒有功能RouteCollection routes名爲MapRootArea這是在Global.asax中如何在ASP.NET MVC3中配置區域

routes.MapRootArea("{controller}/{action}/{id}", 
       "AreasDemo", 
        new { controller = "Home", action = "Index", id = "" }); 

發現當我創建使用MVC3一個新領域,我有一類從AreaRegistration繼承,看起來像下面的那個區域: (這裏博客是地區名稱)

public class BlogsAreaRegistration : AreaRegistration 
{ 
    public override string AreaName 
    { 
     get 
     { 
      return "Blogs"; 
     } 
    } 

    public override void RegisterArea(AreaRegistrationContext context) 
    { 
     context.MapRoute(
      "Blogs_default", 
      "Blogs/{controller}/{action}/{id}", 
      new { action = "Index", id = UrlParameter.Optional } 
     ); 
    } 
} 

請問誰能幫我一下我如何在MVC3中配置區域。任何類型的鏈接也會有幫助。

回答

40

右鍵單擊您的Web項目,然後選擇添加 - >區域...然後鍵入該區域的名稱,Visual Studio將負責其餘的部分,以生成所有必需的類。例如,區域註冊可能是這樣的:

public class AreasDemoAreaRegistration : AreaRegistration 
{ 
    public override string AreaName 
    { 
     get 
     { 
      return "AreasDemo"; 
     } 
    } 

    public override void RegisterArea(AreaRegistrationContext context) 
    { 
     context.MapRoute(
      "AreasDemo_default", 
      "AreasDemo/{controller}/{action}/{id}", 
      new { action = "Index", id = UrlParameter.Optional } 
     ); 
    } 
} 

,並在Application_StartGlobal.asax所有你需要的是:

AreaRegistration.RegisterAllAreas(); 
+0

謝謝你的回答。我怎麼知道區域正確註冊?我在我的共享_layout中使用了這個鏈接,但它並沒有帶我到任何地方@ Html.ActionLink(「Blog」,「About」,「Home」,new {area =「Blog」}) – Imrul 2011-03-09 09:36:04

+0

@Imrul,你的代碼被稱爲「Blogs」,而不是「Blog」,所以試試:@ Html.ActionLink(「Blog」,「About」,「Home」,new {area =「Blogs」})。還要確保在這個區域內有一個'HomeController'。 – 2011-03-09 09:37:19

+0

對不起,拼寫錯誤。我認爲我得到了我的問題,如果我把它渲染到我的_layout它不會生成區域/控制器/動作的鏈接「@ Html.ActionLink(」Blog「,」Index「,」BlogHome「,new {area =」博客 「})」。我在ActionLink助手中做了什麼錯誤?我發現現在在根和區域中不可能有相同的控制器名稱。爲此,我不得不將Home重命名爲BlogHome。 FYI Blog是生成的html,並使用http:// localhost:4135/Blogs/BlogHome/Index訪問BlogHome控制器並顯示頁面。 – Imrul 2011-03-09 09:49:15

5

您可以在根相同的控制器名稱和區域,你只需要定義它。

在您的global.asax,添加routes.maproute的最後一行如下圖所示

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

也,你頃添加控制器的名稱/ ????? AreaRegistration.cs文件

context.MapRoute(
     "Membership_default", 
     "Membership/{controller}/{action}/{id}", 
     new { controller= "Home", action = "Index", id = UrlParameter.Optional } 
    ); 
1

請在下面找到該圖顯示瞭如何在mvc中配置區域。 enter image description here