2014-02-27 24 views
2

我想根據url中的querystring參數動態地改變MVC主題。如何根據查詢字符串值在ASP.Net MVC 5中更改主題?

例如:

  1. 本地主機/ WBE /搜索/ 1
  2. 本地主機/ WBE /搜索/ 2
  3. 本地主機/ WBE /搜索/ 3

這裏1,2, 3是我的客戶密鑰,我有幾個客戶在我的網站中需要不同的主題。那麼,如何根據這個密鑰更改我的網站中的佈局。

等待您的答覆。

Regards, Mallikharjun。

回答

3

我想你可以在你的控制器動作動態設置佈局

public ActionResult Search(int customer) 
{ 
    string layout = ... // function which get layout name with your customer id 

    var viewModel = ... // function which get model 

    return View("Search", layout, viewModel); 
} 

編輯:

我認爲,如果你想有一個更好的解決方案來改變所有的佈局來看,你必須創建一個ActionAttributeFilter將攔截結果並在viewresult中注入佈局

您的過濾器:

public class LayoutChooserAttribute : ActionFilterAttribute 
{ 
    private string _userLayoutSessionKey = "UserLayout"; 


    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     base.OnActionExecuted(filterContext); 


     var result = filterContext.Result as ViewResult; 
     // Only if it's a ViewResult 
     if (result != null) 
     { 
      result.MasterName = GetUserLayout(filterContext); 
     } 
    } 

    private string GetUserLayout(ActionExecutedContext filterContext) 
    { 
     if (filterContext.HttpContext.Session[_userLayoutSessionKey] == null) 
     { 
      // I stock in session to avoid having to start processing every view 
      filterContext.HttpContext.Session[_userLayoutSessionKey] = ...; // process which search the layout 
     } 
     return (string)filterContext.HttpContext.Session[_userLayoutSessionKey]; 
    } 

} 

你的動作變成了:

[LayoutChooser] 
public ActionResult Search(int customer) 
{ 
    var viewModel = ... // function which get model 

    return View("Search", viewModel); 
} 

如果你想要的屬性存在於所有的行動,在FilterConfig.RegisterGlobalFilters靜態方法,你可以添加你的過濾器:

public class FilterConfig 
{ 
    public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
    { 
     ... 
     filters.Add(new LayoutChooserAttribute()); 
    } 
} 
+0

精湛。 ....但是,那麼如何改變這個兒童頁面佈局頁面? – Arjun

+0

我的意思是我想要做這個改變_ViewStart.html頁面佈局屬性...因爲,這個佈局應該像每個主題的母版頁一樣。請指導我...... – Arjun

+1

您希望在開始時選擇佈局,然後在客戶的應用程序的任何地方使用相同的佈局? – binard

相關問題