How do I create the correct route values for this ActionLink?

末鹿安然 提交于 2019-12-03 10:00:24

It think it would be better to create another object with the correct values, instead of using (and potentially altering the current routevalues):

<%=Html.ActionLink("Next Page >", "SearchResults", new {
    search = this.Model,
    page = 1 //or whatever
}) %>

This blog post by Scott Guthrie helped me wrap my head around URL Routing: ASP.NET MVC Framework (Part 2): URL Routing

I love that he included test cases!

You need to override ToString().

Nate

If you are using Razor (I realize OP asked four years ago before Razor was invented, but people finding this maybe using it).

I was able to get something working by using an inline @helper method.

@helper RunnerLink(PersonSearch model, int page)
{
    var routeParms =new RouteValueDictionary(model.GetType().GetProperties().ToDictionary(p => p.Name, p => p.GetValue(model, null)));
    routeParms.Add("page", page.ToString());
    routeParms.Add("Controller", "Property");
    @Html.ActionLink("Search", "Index", routeParms)
}

Usage would be simple --

@RunnerLink(myPersonSearchInstance, 1)

It isn't the most elegant solution, but it works well if you want to pass an object in as a routeValue, but you need to pass additional items, such as Controller, Area or in OPs case page.

You need use RouteLink instead ActionLink. Your code should look something like this

@Html.RouteLink("Next", new {controller = "SearchResults", action = "Index", search=samevalue, page=1 }) 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!