简体   繁体   中英

VB ASP.net MVC Razor: Change View (Template) Programmatically

I want to create a blog with sub-blogs. Each sub-blog would have it's own "theme" variable in the model which would alter the theme. I try to pass the theme variable to the _ViewStart.vbhtml page like so:

@Code

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

However, I get an error:

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

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

How can I change templates, is there a better way?

try it as

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

Just as a warning though, if theme is null then length will fail. Could be better to do

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

Edit: Just for the record, yes setting the different view in the answer you linked ( stackoverflow.com/questions/5059323 ) is better and correct way to do it, but just to note if you wanted to stick to your approach this works for me:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM