How can I execute this type of url in ASP.Net MVC2?

I have a table called "Categories". I want the user to click on the list of categories and then upload a list of all auctions in this category.

Simple enough, right?

I could create an action for each category, for example:

public ActionResult Cellphones() public ActionResult Electronics public ActionResult Clothes public ActionResult Cars public ActionResult RealEstate 

This will result in URLs such as: / Auctions / Apparel and / Auctions / RealEstate. Exactly what I'm looking for.

The problem is that this requires manual grinding. When I add a category, I will have to manually create a new action, and then a new view for it.

Is there a better way to do this?

+4
source share
2 answers

Create one ActionResult:

 public class AuctionController : Controller { public ActionResult AuctionCategoryDetails(string categoryName) { var model = repository.GetAuctionsForCategory(categoryName); return View(model); } } 

Then create one route:

 routes.MapRoute( "AuctionCategoryDetails", "Auctions/{categoryName}", new { controller = "Auction", action = "AuctionCategoryDetails" }); 

So, when you show a list of categories (rather than individual details);

 <% foreach (var category in Model.Categories) { %> <%: Html.RouteLink("Category Details", "AuctionCategoryDetails", new { categoryName = category.CategoryName }); <% } %> 

This will result in a list of such links:

 <a href="/Auctions/Clothes">Category Details</a> <a href="/Auctions/RealEstate">Category Details</a> 

Is that what you are after?

+4
source

Yes, this is called URL routing. You map your categories to a single AuctionController action that serves and displays these categories dynamically depending on what is in the URL.

There's an ASP.NET MVC tutorial out there that covers the basics.

+1
source

All Articles