2009-03-05 140 views
1

我想創建一個多視圖的MVC應用程序,但使用單個控制器。我首先創建了另一個可用於重定向到第二個文件夾的屬性的路線。多視圖單控制器

 public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

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

     routes.MapRoute(
      "Default",            // Route name 
      "{controller}/{action}/{id}",       // URL with parameters 
      new { controller = "Home", action = "Index", id = "" } // Parameter defaults 
     ); 
    } 
    protected void Application_Start() 
    { 
     RegisterRoutes(RouteTable.Routes); 
     SessionManager.Instance.InitSessionFactory("acstech.helpWanted"); 
     ViewEngines.Engines.Clear(); 
     ViewEngines.Engines.Add(new ModeViewEngine()); 
    } 

我接着,通過從WebFormViewEngine降和從〜/查看到〜/ {模式}查看改變的路徑。這工作並正常運行呈現頁面。我碰到的問題是,無論視圖呈現什麼,Html.ActionLink總是使用模式版本。這是實現我的目標的正確方向嗎?如果是這樣,我錯過了什麼讓Action Link正常工作。以下是ViewEngine。這是一個實驗室測試,所以一些自由已經採取。

public class ModeViewEngine : WebFormViewEngine 
{ 
    public ModeViewEngine() 
    { 

    } 

    protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) 
    { 
     string mode = String.Empty; 
     if (controllerContext.RouteData.Values["mode"] != null) 
      mode = controllerContext.RouteData.Values["mode"] as string; 
     return new WebFormView(partialPath.Replace("~/Views", "~/" + mode + "Views"), null); 
    } 

    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) 
    { 
     string mode = String.Empty; 
     if (controllerContext.RouteData.Values["mode"] != null) 
      mode = controllerContext.RouteData.Values["mode"] as string; 
     return new WebFormView(viewPath.Replace("~/Views", "~/" + mode + "Views"), masterPath); 
    } 
} 

回答

0

爲什麼不讓您的控制器根據模式選擇不同的視圖?然後你可以返回你的主視圖或Home_Xml。

我想用自己的方式移動這決定了控制器的和集中的邏輯,但它也需要你創建你有每個模式匹配的視圖。

+0

這將工作,我可以通過創建一個基本的ApplicationController來集中視圖,但願望是有2個獨立的視圖結構。 – Thad 2009-03-05 19:15:52

0

好有關Asp.Net框架偉大的事情是,是,是很可擴展性。我想你應該看看這個鏈接。它將完全符合你的要求。我的opion和作者一起創建一個ActionFilter,並在需要XML甚至JSON視圖的控制器中裝飾你的視圖。我甚至見過所有序列化爲XML的情況都發生在Filter中,並且返回,因此不需要ViewEngine。

http://jesschadwick.blogspot.com/2008/06/aspnet-mvc-using-custom-view-engines.html

1

您是否嘗試過在默認路由添加模式=「」默認數組中?也就是說,據我瞭解,如何從URL中省略「索引」操作,因此理論上應該使其與我相信的默認路線相匹配。