I have a table called Categories. I want the user to click from a list of Categories and then load a listing of all Auctions in that category.
Simple enough, right?
I could create an action for every category, something like:
public ActionResult Cellphones() public ActionResult Electronics public ActionResult Clothes public ActionResult Cars public ActionResult RealEstate
This would generate URLs like: /Auctions/Clothes, and /Auctions/RealEstate. Exactly what I’m looking for.
The problem is this requires manual tinkering. When I add a category, I’ll have to manually create a new action and then a new view for it.
Is there a better way to do this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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 your displaying a list of categories (not individual details);
<% foreach (var category in Model.Categories) { %>
<%: Html.RouteLink("Category Details", "AuctionCategoryDetails", new { categoryName = category.CategoryName });
<% } %>
That will produce a list of links like this:
<a href="/Auctions/Clothes" rel="nofollow noreferrer noopener">Category Details</a> <a href="/Auctions/RealEstate" rel="nofollow noreferrer noopener">Category Details</a>
Is that what your after?
Method 2
Yes, it’s called URL routing. You map your categories to a single AuctionController action, which serves and displays category data dynamically based on what’s in the URL.
There’s a tutorial on the ASP.NET MVC site that covers the ground basics.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0