Skip to content

Instantly share code, notes, and snippets.

@mcintyre321
Created April 23, 2015 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcintyre321/10524d6c7b2e3727ef80 to your computer and use it in GitHub Desktop.
Save mcintyre321/10524d6c7b2e3727ef80 to your computer and use it in GitHub Desktop.
public class ClassnameViewEngine : RazorViewEngine, IViewEngine
{
private readonly Assembly[] _searchAssemblies;
public ClassnameViewEngine(params Assembly[] searchAssemblies)
{
_searchAssemblies = searchAssemblies;
}
//This needs to be initialized to the root namespace of your MVC project.
//Usually, the namespace of your Global.asax's codebehind will do the trick.
private static readonly string RootNamespace = typeof(MvcApplication).Namespace;
private IEnumerable<string> GetPath(ControllerContext controllerContext, string viewName)
{
var type = this._searchAssemblies
.Select(a => a.GetType(viewName))
.FirstOrDefault(t => t != null);
if (type == null) yield break;
//TODO: Cache?
var targetType = type;
var viewFileName = targetType.FullName.Substring(targetType.Assembly.GetName().Name.Length + 1).Replace(".", "/");
yield return (string.Format("~/{0}.cshtml", viewFileName));
}
ViewEngineResult IViewEngine.FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
var paths = GetPath(controllerContext, viewName);
var path = paths.FirstOrDefault(p => VirtualPathProvider.FileExists(p));
if (path != null)
{
return new ViewEngineResult(CreateView(controllerContext, path, null), this);
}
//Check the usual suspects
return base.FindView(controllerContext, viewName, masterName, useCache);
}
public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
{
var paths = GetPath(controllerContext, partialViewName);
var path = paths.FirstOrDefault(p => VirtualPathProvider.FileExists(p));
if (path != null)
{
return new ViewEngineResult(CreateView(controllerContext, path, null), this);
}
//check the usual suspects
return base.FindPartialView(controllerContext, partialViewName, useCache);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment