溢出(即查询字符串)RouteData从控制器返回到视图中
时间:2020-03-06 14:41:11 来源:igfitidea点击:
任何人都知道为什么以下内容不起作用?
我想做的是在视图上形成新链接时,将当前路线数据以及通过匿名对象添加的任何内容复制到新的routedata中。
例如,如果我将参数" page"作为非路由路径(即如果存在查询字符串,则它将路由路径溢出并注入到方法参数中)例如
public ActionResult ChangePage(int? page) { }
并且我希望View在使用助手构建链接时知道更新的页面。我认为最好的方法是使用以下方法:
public ActionResult ChangePage(int? page)
{
if(page.HasValue)
RouteData.Values.Add("Page", page);
ViewData.Model = GetData(page.HasValue ? page.Value : 1);
}
然后,在视图标记中,我可以使用此重载来呈现我的下一个,预览,排序,显示更多(任何相关链接):
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; }
}
}
我发布代码只是为了说明这一点。这行不通,感觉不对...指针?
解决方案
将页面信息传递给ViewData吗?
PagedResultsInfo(或者其他东西)听起来就像一个我们也可以编写的类...我们这样做。

