天天看點

Asp.net MVC23 使用Areas功能的常見錯誤Asp.net MVC23 使用Areas功能的常見錯誤

Asp.net MVC23 使用Areas功能的常見錯誤

一般WEB項目都會不同的頁面區域,如:使用者前台、使用者背景、管理者背景。

通路的URL:

使用者前台:www.domain.com/home/index

使用者背景:www.domain.com/admin/home/index

管理者背景:www.domain.com/manager/home/index

asp.net mvc 2/3 提供了Areas功能來實作

1.打開建立項找到Areas,分别添加admin,manager,添加好後項目結構類似下面

Areas下有各自獨立的Controllers,Models,Views。此外還多了個檔案AreaRegistration為後 綴的.cs檔案. 這個檔案主要的作用是給Areas下的子子產品配置路由。在全局檔案Global.asax中的Application_Start事件裡有這麼一句代 碼 AreaRegistration.RegisterAllAreas()

按上面的需要實作的URL建立好相應的Controllers,Views(home/index)通路URL遇到第一個問題.

第一個問題:

找到了多個與名為“Home”的控制器比對的類型。如果為此請求(“{controller}/{action}/{id}”)提供服務的路由沒有指定命名空間來搜尋比對此請求的控制器,則會發生此情況。如果是這樣,請通過調用采用“namespaces”參數的“MapRoute”方法的重載來注冊此路由

解決方法:

修改AdminAreaRegistration.cs 和 MarengerAreaRegistration.cs 中的路由設定,将其控制器的命名空間傳入給系統,以修改 AdminAreaRegistration.cs 為,另外如果将預設的使用者前台WebSite也放入Areas可以//RegisterRoutes(RouteTable.Routes);

例子:

public

override

void

RegisterArea(AreaRegistrationContext context)

{

  

//直接将命名空間傳入

  context.MapRoute(

    

"Admin_default"

,

    

"Admin/{controller}/{action}/{id}"

,

    

new

{ controller =

"Home"

, action =

"Index"

, id = UrlParameter.Optional },

new

string

[] {

"Demo.Areas.Admin.Controllers"

}

//<span>controllers的命名空間</span>

  );

}

public

override

void

RegisterArea(AreaRegistrationContext context)

{

  

//直接将命名空間傳入

  context.MapRoute(

    

"WebSite_default"

,

    

"{controller}/{action}/{id}"

,

    

new

{ controller =

"Home"

, action =

"Index"

, id = UrlParameter.Optional },

new

string

[] {

"Demo.Areas.WebSite.Controllers"

}

//controllers的命名空間

  );

}

第二個問題: 

@Html.ActionLink對于區域Areas的設定,為了避免在admin/home/index下通路about/index出現admin/about/index about上要new{area=""}

@Html.ActionLink(

"Link Text"

,

"Action"

,

"Controller"

,

new

{ Area=

"<span>AreaName</span>"

},

null

)

<

ul

id="menu">

<

li

>@Html.ActionLink("Home", "Index", "Home", new { area = ""}, null)</

li

>

<

li

>@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)</

li

>

<

li

>@Html.ActionLink("About", "About", "Home", new { area = ""}, null)</

li

>

</

ul

>