Created
April 10, 2014 10:36
-
-
Save feanz/1bfe65cfda51de717170 to your computer and use it in GitHub Desktop.
strongly typed redirect to route result
This file contains 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
protected RedirectToRouteResult RedirectToAction<T>(Expression<Action<T>> action, RouteValueDictionary values) where T : Controller | |
{ | |
var body = action.Body as MethodCallExpression; | |
if (body == null) | |
{ | |
throw new ArgumentException("Expression must be a method call."); | |
} | |
if (body.Object != action.Parameters[0]) | |
{ | |
throw new ArgumentException("Method call must target lambda argument."); | |
} | |
string actionName = body.Method.Name; | |
var attributes = body.Method.GetCustomAttributes(typeof(ActionNameAttribute), false); | |
if (attributes.Length > 0) | |
{ | |
var actionNameAttr = (ActionNameAttribute)attributes[0]; | |
actionName = actionNameAttr.Name; | |
} | |
string controllerName = typeof(T).Name; | |
if (controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)) | |
{ | |
controllerName = controllerName.Remove(controllerName.Length - 10, 10); | |
} | |
RouteValueDictionary defaults = LinkBuilder.BuildParameterValuesFromExpression(body) ?? new RouteValueDictionary(); | |
values = values ?? new RouteValueDictionary(); | |
values.Add("controller", controllerName); | |
values.Add("action", actionName); | |
if (defaults != null) | |
{ | |
foreach (var pair in defaults.Where(p => p.Value != null)) | |
{ | |
values.Add(pair.Key, pair.Value); | |
} | |
} | |
return new RedirectToRouteResult(values); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment