Skip to content

Instantly share code, notes, and snippets.

@sebmarkbage
Created August 10, 2012 07:51
Show Gist options
  • Save sebmarkbage/3312466 to your computer and use it in GitHub Desktop.
Save sebmarkbage/3312466 to your computer and use it in GitHub Desktop.
Controller
public static class UrlHelperExtensions
{
public static string SmartAction(this UrlHelper url, object values)
{
return SmartAction(url, null, values);
}
public static string SmartAction(this UrlHelper url, RouteValueDictionary valueCollection)
{
return SmartAction(url, null, valueCollection);
}
public static string SmartAction(this UrlHelper url, string actionName, object values)
{
return SmartAction(url, actionName, null, new RouteValueDictionary(values));
}
public static string SmartAction(this UrlHelper url, string actionName, RouteValueDictionary valueCollection)
{
return SmartAction(url, actionName, null, valueCollection);
}
public static string SmartAction(this UrlHelper url, string actionName, string controllerName, object values)
{
return SmartAction(url, actionName, controllerName, new RouteValueDictionary(values));
}
public static string SmartAction(this UrlHelper url, string actionName, string controllerName, RouteValueDictionary valueCollection)
{
var resultingCollection = new RouteValueDictionary();
foreach (var pair in valueCollection)
{
var value = pair.Value;
var type = value == null ? null : value.GetType();
if (value != null && (type.IsArray || type.IsAssignableFrom(typeof(IEnumerable))))
{
var i = 0;
foreach (var v in (IEnumerable)value)
{
resultingCollection.Add(pair.Key + "[" + i + "]", v);
i++;
}
}
else if (value != null && type.IsClass && type != typeof(string))
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value))
{
resultingCollection.Add(pair.Key + "." + property.Name, property.GetValue(value));
}
}
else
{
resultingCollection.Add(pair.Key, pair.Value);
}
}
return url.Action(actionName, controllerName, resultingCollection);
}
}
public class SmartController : Controller
{
protected override IActionInvoker CreateActionInvoker()
{
return new SmartControllerActionInvoker();
}
}
public class SmartControllerActionInvoker : ControllerActionInvoker
{
protected override ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
{
if (actionReturnValue == null) return new EmptyResult();
return (actionReturnValue as ActionResult) ?? new JsonResult { Data = actionReturnValue, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment