2012-07-26 185 views
1

我想創建一個包含子博客的博客。每個子博客都會在模型中擁有自己的「主題」變量,這會改變主題。我嘗試主題變量傳遞給_ViewStart.vbhtml頁面,如下所示:VB ASP.net MVC Razor:以編程方式更改視圖(模板)

@Code

@((@ViewBag.Theme.length > 0) ? Layout = @ViewBag.Theme : Layout = "~/Views/Shared/_Layout.vbhtml") 
    End Code 

但是,我得到一個錯誤:

說明:該請求提供服務所需資源的編譯過程中出現錯誤。請查看以下具體的錯誤細節並適當修改您的源代碼。

Compiler Error Message: BC30201: Expression expected.

Source Error:

Line 5: *@ Line 6: Line 7: @((@ViewBag.Theme.length > 0) ? Layout = @ViewBag.Theme : Layout = "~/Views/Shared/_Layout.vbhtml") Line 8: Line 9: End Code

Source File: C:\Users\darchual\documents\visual studio 2010\Projects\GemcoBlog\GemcoBlog\Views_ViewStart.vbhtml Line: 7

如何更改模板,有沒有更好的方法?

回答

0

嘗試,因爲

@{ 
    Layout = (ViewBag.Theme.length > 0) ? ViewBag.Theme : "~/Views/Shared/_Layout.vbhtml" 
} 

正如一個警告不過,如果主題爲null,則長度將失敗。可以更好地做

@{ 
    Layout = !String.IsNullOrWhiteSpace(ViewBag.Theme) ? ViewBag.Theme : "~/Views/Shared/_Layout.vbhtml" 
} 

編輯:只是爲了記錄在案,是設置在回答不同的看法您鏈接(stackoverflow.com/questions/5059323)是更好的,正確的方式來做到這一點,只是要注意,如果你想堅持你的方法,這對我的作品:

@{ 
    Layout = !String.IsNullOrWhiteSpace((String)ViewContext.ViewData["Theme"]) ? (String)ViewContext.ViewData["Theme"] : "~/Views/Shared/_Layout.cshtml"; 
} 
+0

我嘗試過,但它給了我一個語法錯誤的「@ {」它說,「說明:維修本所需資源的編譯過程中出現錯誤請仔細閱讀以下具體的錯誤細節並適當修改您的源代碼。「在我的VS2010中,它說:「錯誤'ViewBag'未被聲明,由於它的保護級別,它可能不可訪問。」 – user1477388 2012-07-26 15:27:11

+0

@ user1477388對不起,只是注意到你試圖從無法訪問ViewBag的_ViewStart中執行它。您可以使用PageData(如http://stackoverflow.com/questions/4834045/how-do-i-set-viewbag-properties-on-viewstart-cshtml中所示)或將其聲明在頁面的頂部(包括哪裏ViewBag.Title通常被聲明)。 – Manatherin 2012-07-26 15:30:17

+0

@ user1477388在http://stackoverflow.com/questions/6578029/why-cant-viewstart-cshtml-access-the-viewbag-object中顯示的另一種替代方法。您可能可以通過'ViewContext.ViewData [「Theme」]訪問它' – Manatherin 2012-07-26 15:34:24

相關問題