C#MVC3中的复杂URL

时间:2012-02-15 13:59:58

标签: c# asp.net-mvc-3 url routing

我是MVC3的新手,无法解决这个问题。 我正在创建一个简短的博客,其中包含分类,每个帖子可能都有一些标签。 如果我向用户显示帖子,我在那里分页,其中url就像localhost / Posts / 1,其中“1”是页面的编号。 但是,如果我只想显示某些类别或某些标签的帖子,我该怎么办呢? 它的格式为localhost / Posts / Categories / 1,其中“1”是类别的id或localhost / Posts / Tags / tag1其中“tag1”是特定标签 我想将其全部更改为localhost / Posts / Page / 1或localhost / Posts / Categories / 1 / Page / 1或localhost / Posts / Tags / tag1 / Page / 1格式,但我真的无法了解如何在控制器中实现这一点。 所以我的问题是:如何让控制器中的方法接受这些复杂的网址?

我想这与路由有关,但找不到我的问题的任何解释。

非常感谢您的帮助。

我的代码:

public ActionResult Tags(string id)
{
  Tag tag = GetTag(id);
  ViewBag.IdUser = IDUser;
  if (IDUser != -1)
  {
    ViewBag.IsAdmin = IsAdmin;
    ViewBag.UserName = model.Users.Where(x => x.IDUser == IDUser).First().Name;
  }
  return View("Index", tag.Posts.OrderByDescending(x => x.DateTime));
}

public ActionResult Index(int? id)
{
  int pageNumber = id ?? 0;
  IEnumerable<Post> posts =
            (from post in model.Posts
             where post.DateTime < DateTime.Now
             orderby post.DateTime descending
             select post).Skip(pageNumber * PostsPerPage).Take(PostsPerPage + 1);
  ViewBag.IsPreviousLinkVisible = pageNumber > 0;
  ViewBag.IsNextLinkVisible = posts.Count() > PostsPerPage;
  ViewBag.PageNumber = pageNumber;
  ViewBag.IdUser = IDUser;
  if (IDUser != -1)
  {
    ViewBag.IsAdmin = IsAdmin;
    ViewBag.UserName = model.Users.Where(x => x.IDUser == IDUser).First().Name;
  }
  return View(posts.Take(PostsPerPage));
  }

1 个答案:

答案 0 :(得分:2)

创建新路由以将这些URL模式定向到您的控制器(或其他控制器,视情况而定)

http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs

例如,此路线定义

   routes.MapRoute(
                "CategoryPage",                                              // Route name
                "Posts/Categories/{CategoryID}/Page/{PageID}",                           // URL with parameters
                new { controller = "Home", action = "ViewPage", CategoryID = "", PageID="" }  // Parameter defaults
            );

将在HomeController中通过此操作获取:

public ActionResult ViewPage(int CategoryID, int PageID)
相关问题