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开发者_Python百科
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?
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">Category Details</a>
<a href="/Auctions/RealEstate">Category Details</a>
Is that what your after?
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.
精彩评论