Created
July 4, 2012 23:07
-
-
Save Buildstarted/3049985 to your computer and use it in GitHub Desktop.
ControllerExtensions to allow return of typed views
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class ControllerExtensions | |
{ | |
//should be safe for most controllers | |
private static MethodInfo _viewMethod; | |
private static readonly ConcurrentDictionary<Type, string> CachedPathNames = new ConcurrentDictionary<Type, string>(); | |
public static ActionResult TypedView(this Controller controller, Type type) | |
{ | |
return TypedView(controller, type, null, null); | |
} | |
public static ActionResult TypedView(this Controller controller, Type type, object model) | |
{ | |
return TypedView(controller, type, null, model); | |
} | |
public static ActionResult TypedView(this Controller controller, Type type, string masterName, object model) | |
{ | |
var virtualPath = GetVirtualPath(type); | |
var method = GetViewMethod(controller); | |
return method.Invoke( | |
controller, | |
new[] | |
{ | |
virtualPath, | |
masterName, | |
model | |
} | |
) as ActionResult; | |
} | |
private static string GetVirtualPath(Type type) | |
{ | |
string virtualPath; | |
if (CachedPathNames.TryGetValue(type, out virtualPath)) | |
{ | |
return virtualPath; | |
} | |
var attributes = type.GetCustomAttributes(typeof(PageVirtualPathAttribute), true); | |
virtualPath = (attributes.First() as PageVirtualPathAttribute).VirtualPath; | |
return CachedPathNames.GetOrAdd(type, virtualPath); | |
} | |
private static MethodInfo GetViewMethod(Controller controller) | |
{ | |
if (_viewMethod == null) { | |
_viewMethod = controller.GetType() | |
.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic) | |
.First(f => | |
f.Name == "View" | |
&& f.GetParameters().Length == 3 | |
); | |
} | |
return _viewMethod; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment