C#MVC3中的复杂URL

本文关键字:URL 复杂 C#MVC3 | 更新日期: 2023-09-27 18:24:36

我是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格式,但我真的找不到如何在控制器中实现这一点。所以我的问题是:如何在控制器中创建方法来接受这些复杂的url?

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

非常感谢你的帮助。

我的代码:

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));
  }

C#MVC3中的复杂URL

创建新的路由,将这些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)