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" } //controllers的命名空間
  );

}
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="AreaName" }, 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>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM