我怎样才能做到在ASP.Net MVC2这种类型的URL? [英] How can I accomplish this type of URL in ASP.Net MVC2?
问题描述
我有一个表称为类别。我希望用户从类别列表单击,然后在该类别加载所有拍卖列表。
够简单了吧?
我可以为每个类别创建一个动作,是这样的:
公众的ActionResult手机()
公众的ActionResult电子
公众的ActionResult衣服
公众的ActionResult汽车
公众的ActionResult房地产
这会产生这样的URL:/拍卖/服装,和/拍卖/房地产。正是我要找的。 P>
问题是这需要人工修补。当我添加一个类,我将不得不手动创建一个新的动作,然后一个新的视角。
有没有更好的方法来做到这一点?
制作一个ActionResult的:
公共类AuctionController:控制器
{
公众的ActionResult AuctionCategoryDetails(字符串categoryName)
{
VAR模型= repository.GetAuctionsForCategory(类别名);
返回查看(模型);
}
}
然后创建一个路由:
routes.MapRoute(
AuctionCategoryDetails
拍卖会/ {}类别名称,
新{控制器=拍卖,行动=AuctionCategoryDetails});
所以,当你的显示类(而不是个人的详细信息)的列表;
<%的foreach(在Model.Categories VAR类){%GT;
<%:Html.RouteLink(类别详细信息,AuctionCategoryDetails,新的类别名称{= category.CategoryName});
<%}%GT;
这会产生这样的链接列表:
< A HREF =/拍卖/服装>分类详细资料及LT; / A>
< A HREF =/拍卖/房地产>分类详细资料及LT; / A>
那是你的后?
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?
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?
这篇关于我怎样才能做到在ASP.Net MVC2这种类型的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!