2012-02-16 39 views
0

我希望能夠根據數據庫中的設置更改_Layout.cshtml視圖。
據我所知,它可能是在_ViewStart.cshml視圖中完成的。如何在ASP.Net中動態更改主題和_Layout MVC4

我正在使用EF 4.2並希望改編一個不會破壞任何設計模式的解決方案。

不知道如何去做這個在MVC。

在web表單中,我可以很容易地在masterpage的代碼隱藏中做到這一點。

我做這樣的事情在我的基本控制器:

public abstract class BaseController : Controller 
{ 
    private IUserRepository _userRepository; 


    protected BaseController() 
     : this(
      new UserRepository()) 
    { 
    } 


    public BaseController(IUserRepository userRepository) 
    { 
     _userRepository = userRepository; 
    } 

我在FunnelWeb源看起來很好,但我不完全得到他們是如何注入東西..

+0

將它傳遞給ViewBag。添加這個ViewStart,ViewContext.Controller.ViewBag.Layout。 – user960567 2012-02-16 04:04:06

+1

爲主題,你可以看看這個現場演示:http://prodinner.aspnetawesome.com並在這裏下載http://prodinner.codeplex.com – Omu 2012-02-16 10:42:52

回答

3

老問題,但任何人在這裏跨越這個問題未來是使用操作過濾器一個很好的解決方案屬性

public class LoadUserLayoutAttribute : ActionFilterAttribute 
{ 
    private readonly string _layoutName; 
    public LoadUserLayoutAttribute() 
    { 
     _layoutName = MethodToGetLayoutNameFromDB(); 
    } 

    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     base.OnActionExecuted(filterContext); 
     var result = filterContext.Result as ViewResult; 
     if (result != null) 
     { 
      result.MasterName = _layoutName; 
     } 
    } 
} 

然後,您可以將屬性添加到您的基本控制器(或這個自定義屬性:

[LoadUserLayout] 
    public abstract class BaseController : Controller 
    { 
     ... 
    } 
2

將此代碼添加到BundleConfig類的RegisterBundles方法中。請注意,我正在爲每個css創建一個單獨的包,以便我不將每個css都呈現給客戶端。我可以選擇要在共享_Layout.cshtml視圖的HEAD部分中呈現哪個包。

bundles.Add(new StyleBundle("~/Content/Ceruleancss").Include(
    "~/Content/bootstrapCerulean.min.css", 
     "~/Content/site.css")); 

bundles.Add(new StyleBundle("~/Content/defaultcss").Include(
       "~/Content/bootstrap.min.css", 
       "~/Content/site.css")); 

然後在shared_Layout.cshtml中放入一些邏輯來渲染適當的包。由於這個佈局視圖會觸發每個頁面,因此這是放置它的好地方。

我認爲這種方法可以用於品牌,如果你支持你的應用程序的多個軍團。它也可以用來提供用戶自定義的風格,我想。

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8" /> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title>@ViewBag.Title - Contoso University</title> 

@{ 

    if (HttpContext.Current.User.Identity.Name == "MARK") 
    { 
     @Styles.Render("~/Content/defaultcss"); 
    } 
    else 
    { 
     @Styles.Render("~/Content/Ceruleancss"); 
    } 

}