Добавить строку запроса в качестве словаря значений маршрута в ActionLink
Я пытаюсь создать ActionLink для экспорта данных из сетки. Сетка фильтруется значениями из строки запроса. Вот пример URL:
http://www.mysite.com/GridPage?Column=Name&Direction=Ascending&searchName=text
Здесь код для добавления моего ActionLink на страницу:
@Html.ActionLink("Export to Excel", // link text
"Export", // action name
"GridPage", // controller name
Request.QueryString.ToRouteDic(), // route values
new { @class = "export"}) // html attributes
Когда отображается ссылка, URL-адрес таков:
http://www.mysite.com/GridPage/Export?Count=3&Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D
Что я делаю неправильно?
Ответы
Ответ 1
Попробуйте следующее:
Я не уверен, что это самый чистый или самый правильный способ, но он работает
Я не использовал ваш метод расширения. Вам нужно будет реинтегрировать это:
@{
RouteValueDictionary tRVD = new RouteValueDictionary(ViewContext.RouteData.Values);
foreach (string key in Request.QueryString.Keys )
{
tRVD[key]=Request.QueryString[key].ToString();
}
}
затем
@Html.ActionLink("Export to Excel", // link text
"Export", // action name
"GridPage", // controller name
tRVD,
new Dictionary<string, object> { { "class", "export" } }) // html attributes
Результаты в
![Results]()
с экспортом класса ![enter image description here]()
Ответ 2
Если вы посмотрите здесь:
http://msdn.microsoft.com/en-us/library/system.web.mvc.html.linkextensions.actionlink.aspx
//You are currently using:
ActionLink(HtmlHelper, String, String, String, Object, Object)
//You want to be using:
ActionLink(HtmlHelper, String, String, String, RouteValueDictionary, IDictionary<String, Object>)
Ответ 3
Перекрестная регистрация из Как получить значения QueryString в документе RouteValueDictionary с помощью Html.BeginForm()?
Здесь добавляется вспомогательное расширение, поэтому вы можете сбрасывать запрос с помощью любого метода, принимающего RouteValueDictionary
.
/// <summary>
/// Turn the current request querystring into the appropriate param for <code>Html.BeginForm</code> or <code>Html.ActionLink</code>
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
/// <remarks>
/// See discussions:
/// * https://stackoverflow.com/info/4675616/how-do-i-get-the-querystring-values-into-a-the-routevaluedictionary-using-html-b
/// * https://stackoverflow.com/info/6165700/add-query-string-as-route-value-dictionary-to-actionlink
/// </remarks>
public static RouteValueDictionary QueryStringAsRouteValueDictionary(this HtmlHelper html)
{
// shorthand
var qs = html.ViewContext.RequestContext.HttpContext.Request.QueryString;
// because LINQ is the (old) new black
return qs.AllKeys.Aggregate(new RouteValueDictionary(html.ViewContext.RouteData.Values),
(rvd, k) => {
// can't separately add multiple values `?foo=1&foo=2` to dictionary, they'll be combined as `foo=1,2`
//qs.GetValues(k).ForEach(v => rvd.Add(k, v));
rvd.Add(k, qs[k]);
return rvd;
});
}