asp.net-mvc-3 – 我可以传递视图模型到动作链接来生成路由吗?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 我可以传递视图模型到动作链接来生成路由吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要创建一个基于我的搜索条件的链接.例如:
  1. localhost/Search?page=2&Location.PostCode=XX&Location.Country=UK&IsEnabled=true

链接中的参数是Searchviewmodel中属性的值.

理想情况下,我想要做一些事情:

  1. @Html.ActionLink("Search","User",Model.SearchCriteria)

这是否被默认支持,还是需要将我的视图模型的属性传递给RouteValueDictionary类型对象,然后使用?

我的目标是编写一个页面助手,它将生成页码,并将搜索条件参数附加到生成链接.

例如.

  1. @Html.GeneratePageLinks(Model.PagingInfo,x => Url.Action("Index"),Model.SearchCriteria)

我将您的解决方案与PRO ASP.NET MVC 3书籍的建议相结合,最终结合如下:

帮助生成链接.有趣的部分是pageUrlDelegate参数,后来用于调用Url.Action生成链接

  1. public static MvcHtmlString PageLinks(this HtmlHelper html,PagingInfoviewmodel pagingInfo,Func<int,String> pageUrlDelegate)
  2. {
  3. StringBuilder result = new StringBuilder();
  4. for (int i = 1; i <= 5; i++)
  5. {
  6. TagBuilder tagBuilder = new TagBuilder("a");
  7. tagBuilder.MergeAttribute("href",pageUrlDelegate(i));
  8. tagBuilder.InnerHtml = i.ToString();
  9. result.Append(tagBuilder.ToString());
  10. }
  11.  
  12. return MvcHtmlString.Create(result.ToString());
  13. }

然后在视图模型中:

  1. @Html.PageLinks(Model.PagingInfo,x => Url.Action("Index","Search",new RouteValueDictionary()
  2. {
  3. { "Page",x },{ "Criteria.Location.PostCode",Model.Criteria.Location.PostCode },{ "Criteria.Location.Town",Model.Criteria.Location.Town},{ "Criteria.Location.County",Model.Criteria.Location.County}
  4. }))
  5. )

我仍然不满足Strings中的物业名称,但现在必须要做.

谢谢 :)

解决方法

Ideally I’d like to have something on the lines of:

@Html.ActionLink("Search",Model.SearchCriteria)

不幸的是,这是不可能的.你必须逐个传递属性.你可以使用一个RouteValueDictionary的重载:

  1. @Html.ActionLink(
  2. "Search",new RouteValueDictionary(new Dictionary<string,object>
  3. {
  4. { "Location.PostCode",Model.SearchCriteria.PostCode },{ "Location.Country",Model.SearchCriteria.Country },{ "IsEnabled",Model.IsEnabled },})
  5. )

当然最好编写一个自定义的ActionLink帮助器来做到这一点:

  1. public static class HtmlExtensions
  2. {
  3. public static IHtmlString GeneratePageLink(this HtmlHelper<Myviewmodel> htmlHelper,string linkText,string action)
  4. {
  5. var model = htmlHelper.ViewData.Model;
  6. var values = new RouteValueDictionary(new Dictionary<string,object>
  7. {
  8. { "Location.PostCode",model.SearchCriteria.PostCode },model.SearchCriteria.Country },model.IsEnabled },});
  9. return htmlHelper.ActionLink(linkText,action,values);
  10. }
  11. }

接着:

  1. @Html.GeneratePageLink("some page link text","index")

另一种可能性是仅传递ID,并且控制器操作从最初在执行该视图的控制器操作中提取相应的模型和值.

猜你在找的asp.Net相关文章