Asp.net MVC 网站换肤需要使用不同模板,可以通过自定义视图引擎来实现这个功能。这里我偷懒,直接继承 VirtualPathProviderViewEngine来实现。
核心代码如下:
ThemeViewEngine.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Mvc;
namespace
MvcSkinDemo.Code
{
public
class
ThemeViewEngine : VirtualPathProviderViewEngine
{
private
string
_theme;
/// <summary>
/// 使用的主题名称
/// </summary>
public
string
Theme
{
get
{
return
_theme; }
set
{
_theme =
string
.IsNullOrEmpty(value) ?
"Default"
: value;
SetLocationFormats(_theme);
}
}
public
ThemeViewEngine(
string
themeName)
{
Theme = themeName;
}
/// <summary>
/// 设置视图的搜索路径集合
/// </summary>
/// <param name="themeName">主题名</param>
private
void
SetLocationFormats(
string
themeName)
{
base
.MasterLocationFormats =
new
[] {
"~/Views/Themes/"
+ themeName +
"/{1}/{0}.master"
,
"~/Views/Themes/"
+ themeName +
"/Shared/{0}.master"
,
"~/Views/Themes/Shared/{0}.master"
};
base
.ViewLocationFormats =
new
[] {
"~/Views/Themes/"
+ themeName +
"/{1}/{0}.aspx"
,
"~/Views/Themes/"
+ themeName +
"/{1}/{0}.ascx"
,
"~/Views/Themes/"
+ themeName +
"/Shared/{0}.aspx"
,
"~/Views/Themes/"
+ themeName +
"/Shared/{0}.ascx"
,
"~/Views/Themes/Shared/{1}/{0}.aspx"
,
"~/Views/Themes/Shared/{1}/{0}.ascx"
,
"~/Views/Themes/Shared/{0}.aspx"
,
"~/Views/Themes/Shared/{0}.ascx"
};
base
.PartialViewLocationFormats =
base
.ViewLocationFormats;
}
protected
override
IView CreatePartialView(ControllerContext controllerContext,
string
partialPath)
{
return
new
WebFormView(partialPath);
}
protected
override
IView CreateView(ControllerContext controllerContext,
string
viewPath,
string
masterPath)
{
return
new
WebFormView(viewPath, masterPath);
}
}
}
|
Global.asax 设置如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
protected
void
Application_Start()
{
AreaRegistration.RegisterAllAreas();
///初始化ViewEngine
InitViewEngine();
RegisterRoutes(RouteTable.Routes);
}
private
void
InitViewEngine()
{
ViewEngines.Engines.Clear();
//在RC中目前还没找到好的在Controller中修改ViewEngine的办法
//只好在这里将顺序换一下,对性能有一点影响
//ViewEngines.Engines.Add(new ThemeViewEngine(theme));
ViewEngines.Engines.Add(
new
ThemeViewEngine(
"default"
));
}
|
切换视图引擎:
1
|
(ViewEngines.Engines[0]
as
ThemeViewEngine).Theme =
"green"
;
|
项目结构如下:
如果你想定义强大的视图引擎,可以参考这个:
http://www.cnblogs.com/webabcd/archive/2009/05/14/1456453.html