Anyone understand why the following doesn't work. What I want to do is copy current route data plus whatever I add via an anonymous object into new routedata when forming new links on the view. For example if I have the parameter "page" as a non route path (i.e. so it overflows the route path and its injected into the method parameter if a querystirng is present) e.g.public ActionResult ChangePage(int? page) { } and I want the View to know the updated page when building links using helpers. I thought the best way to do this is with the following
public ActionResult ChangePage(int? page) { if(page.HasValue) RouteData.Values.Add("Page", page); ViewData.Model = GetData(page.HasValue ? page.Value : 1); }
Then in the view markup I can render my next, preview, sort, showmore (any links relevant) with this overload:
public static class Helpers
{
public static string ActionLinkFromRouteData(this HtmlHelper helper, string linkText, string actionName, object values)
{
RouteValueDictionary routeValueDictionary = new RouteValueDictionary();
foreach(var routeValue in helper.ViewContext.RouteData.Values)
{
if(routeValue.Key != "controller" && routeValue.Key != "action")
{
routeValueDictionary[routeValue.Key] = routeValue;
}
}
foreach(var prop in GetProperties(values))
{
routeValueDictionary[prop.Name] = prop.Value;
}
return helper.ActionLink(linkText, actionName, routeValueDictionary;
}
private static IEnumerable<PropertyValue> GetProperties(object o)
{
if (o != null) {
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(o);
foreach (PropertyDescriptor prop in props) {
object val = prop.GetValue(o);
if (val != null) {
yield return new PropertyValue { Name = prop.Name, Value = val };
}
}
}
}
private sealed class PropertyValue
{
public string Name { get; set; }
public object Value { get; set; }
}
}
I post code only to illustrate point. This doesnt work and doesnt feel right.. Pointers?