Reputation: 183
I am new to MVC3 and cannot move with this problem. I am making a simple blog with posts, that are divided into categories and each post may have some tags. If I show posts to user, I have paging there, where url is like localhost/Posts/1, where "1" is number of the page. But how can I do this if I want to show posts only from some category or with some tag? It is in format localhost/Posts/Categories/1, where "1" is id of the category or localhost/Posts/Tags/tag1 where "tag1" is particular tag I would like to change it all to be in format localhost/Posts/Page/1 or localhost/Posts/Categories/1/Page/1 or localhost/Posts/Tags/tag1/Page/1, but I really cannot find out how to achieve this in controller. So my question is: How to make methods in controller to accept these complex urls?
I guess it has something to do with routing, but couldn't find any explanation of my problem.
Thanks a lot for any help.
My code:
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));
}
Upvotes: 2
Views: 477
Reputation: 4412
Create new routes to direct those URL patterns to your controller (or another contoller, as appropriate)
For example, this route definition
routes.MapRoute(
"CategoryPage", // Route name
"Posts/Categories/{CategoryID}/Page/{PageID}", // URL with parameters
new { controller = "Home", action = "ViewPage", CategoryID = "", PageID="" } // Parameter defaults
);
Would be picked up by this action in the HomeController:
public ActionResult ViewPage(int CategoryID, int PageID)
Upvotes: 2