作爲替代方案,您可以覆蓋特定的控制器視圖引擎的位置,而不會影響視圖引擎爲其他控制器。
這些是我正在開發的產品的一些片段,但它顯示了我的控制器之一的構造函數,以及我特別爲從KBRenderMvcController繼承的控制器製作的視圖引擎。
因此,任何基於KBRenderMvcController的控制器都將擁有我的視圖引擎。
然而,我沒有清除視圖引擎集合,這是相關的。因爲我希望我的產品正在使用的視圖回退到默認位置。
總之,如果您刪除\ App_plugins \產品\查看\ MyView的,而是創建一個\查看\ MyView的它仍然從\瀏覽渲染\ MyView的來代替。
另外,在視圖引擎我演示代碼,確定所用控制器的類型,如果它不是一個目標控制器我回空視圖位置,這樣它們纔不會被用於其他控制器。
#region Constructor
public KBRenderMvcController()
: base()
{
viewEngine = new KBFrontEndViewEngine();
if (!this.ViewEngineCollection.Contains(viewEngine))
this.ViewEngineCollection.Insert(0, viewEngine);
}
#endregion
public class KBFrontEndViewEngine : RazorViewEngine
{
#region Fields
private static bool _Initialized = false;
private static string[] viewLocationFormats = null;
private static string[] partialViewLocationFormats = null;
private static string[] viewEngineFileExtensions = new string[] { "cshtml" };
#endregion
#region Constructor
public KBFrontEndViewEngine()
{
if (!_Initialized)
{
viewLocationFormats = new string[]
{
string.Concat(KBApplicationCore.PluginRelUrl, "/Views/{1}/{0}.cshtml"),
string.Concat(KBApplicationCore.PluginRelUrl, "/Views/Partials/{0}.cshtml")
};
partialViewLocationFormats = new string[]
{
string.Concat(KBApplicationCore.PluginRelUrl, "/Views/{1}/Partials/_partial{0}.cshtml"),
string.Concat(KBApplicationCore.PluginRelUrl, "/Views/Partials/_partial{0}.cshtml"),
string.Concat(KBApplicationCore.PluginRelUrl, "/Views/{1}/Dialogs/_dialog{1}.cshtml"),
string.Concat(KBApplicationCore.PluginRelUrl, "/Views/Dialogs/_dialog{1}.cshtml"),
};
_Initialized = true;
}
base.ViewLocationFormats = viewLocationFormats;
base.PartialViewLocationFormats = partialViewLocationFormats;
base.MasterLocationFormats = viewLocationFormats;
base.FileExtensions = viewEngineFileExtensions;
}
#endregion
#region Methods
//Don't run on requests that are not for our hijacked controllers
public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
{
Type controllerType = controllerContext.Controller.GetType();
Type baseType = controllerType.BaseType;
if ((baseType != null) && (baseType.Name == "KBRenderMvcController`1") || (baseType.Name == "KBFrontEndBaseSurfaceController"))
return base.FindPartialView(controllerContext, partialViewName, useCache);
else
return new ViewEngineResult(new List<string>());
}
#endregion
}
如果你不想幹到底,並創建自己的ViewEngine你可以設置的位置格式在App_Start現有的發動機:ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(新WebFormViewEngine { LocationFormats =新的字符串[] { 「〜/查看/ {1}/{0}的.html」} ... }); – Cargowire 2010-12-20 18:38:05