我需要创建一个基于我的搜索条件的链接.例如:
localhost/Search?page=2&Location.PostCode=XX&Location.Country=UK&IsEnabled=true
理想情况下,我想要做一些事情:
@Html.ActionLink("Search","User",Model.SearchCriteria)
这是否被默认支持,还是需要将我的视图模型的属性传递给RouteValueDictionary类型对象,然后使用?
我的目标是编写一个页面助手,它将生成页码,并将搜索条件参数附加到生成的链接.
例如.
@Html.GeneratePageLinks(Model.PagingInfo,x => Url.Action("Index"),Model.SearchCriteria)
我将您的解决方案与PRO ASP.NET MVC 3书籍的建议相结合,最终结合如下:
帮助生成链接.有趣的部分是pageUrlDelegate参数,后来用于调用Url.Action生成链接:
public static MvcHtmlString PageLinks(this HtmlHelper html,PagingInfoviewmodel pagingInfo,Func<int,String> pageUrlDelegate) { StringBuilder result = new StringBuilder(); for (int i = 1; i <= 5; i++) { TagBuilder tagBuilder = new TagBuilder("a"); tagBuilder.MergeAttribute("href",pageUrlDelegate(i)); tagBuilder.InnerHtml = i.ToString(); result.Append(tagBuilder.ToString()); } return MvcHtmlString.Create(result.ToString()); }
然后在视图模型中:
@Html.PageLinks(Model.PagingInfo,x => Url.Action("Index","Search",new RouteValueDictionary() { { "Page",x },{ "Criteria.Location.PostCode",Model.Criteria.Location.PostCode },{ "Criteria.Location.Town",Model.Criteria.Location.Town},{ "Criteria.Location.County",Model.Criteria.Location.County} })) )
我仍然不满足Strings中的物业名称,但现在必须要做.
谢谢 :)
解决方法
Ideally I’d like to have something on the lines of:
@Html.ActionLink("Search",Model.SearchCriteria)
不幸的是,这是不可能的.你必须逐个传递属性.你可以使用一个RouteValueDictionary的重载:
@Html.ActionLink( "Search",new RouteValueDictionary(new Dictionary<string,object> { { "Location.PostCode",Model.SearchCriteria.PostCode },{ "Location.Country",Model.SearchCriteria.Country },{ "IsEnabled",Model.IsEnabled },}) )
当然最好编写一个自定义的ActionLink帮助器来做到这一点:
public static class HtmlExtensions { public static IHtmlString GeneratePageLink(this HtmlHelper<Myviewmodel> htmlHelper,string linkText,string action) { var model = htmlHelper.ViewData.Model; var values = new RouteValueDictionary(new Dictionary<string,object> { { "Location.PostCode",model.SearchCriteria.PostCode },model.SearchCriteria.Country },model.IsEnabled },}); return htmlHelper.ActionLink(linkText,action,values); } }
接着:
@Html.GeneratePageLink("some page link text","index")
另一种可能性是仅传递ID,并且控制器操作从最初在执行该视图的控制器操作中提取相应的模型和值.