【发布时间】:2017-01-22 08:57:30
【问题描述】:
我有一个索引页面,它显示类别(具有属性:id 和名称)和 URL 请求:http://localhost:62745/home/index。
当我点击一个类别时,我被带到http://localhost:62745/Home/Products/6。
我想让 URL 更详细,并将之前 URL 中的 Category Id 属性 6 替换为刚刚单击的 Category 的 name 属性。
我的路线配置如下所示:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Categories",
url: "{controller}/{action}/{categoryName}",
defaults: new { controller = "Category", action = "Index", categoryName = UrlParameter.Optional }
);
}
}
第一个MapRoute() 方法已经实现。我添加了第二个希望解决我的问题,但它没有。
这是我对产品的控制器操作:
// GET: Product
public async Task<ActionResult> Index(int? id, string categoryName)
{
var products = (await db.Categories.Where(c => c.Id == id)
.SelectMany(p => p.Products.Select(x => new ProductViewModel { Id = x.Id, Name = x.Name, ByteImage = x.Image, Price = x.Price}))
.ToListAsync());
categoryName = db.Categories.Where(c => c.Id == id).Select(c => c.Name).ToString();
if (products == null)
{
return HttpNotFound();
}
return View(new ProductIndexViewModel{ Products = products, CategoryId = id });
}
【问题讨论】:
-
我认为
id是Category名称的数字标识符?如果是这种情况,我还假设id是唯一的,而Category没有唯一约束。尝试使用人类可读的Category作为您尝试关闭的值会导致问题。你想要完成什么?这仅仅是为了在您的查询字符串中有一个可读的值吗? -
需要注意的一点是,在映射路线时,您总是希望从顶部的最具体到底部的最一般。所以默认路由需要在列表中的最后一个,而不是你目前拥有的第一个。否则其他路线将没有机会
-
请参阅Why map special routes first before common routes in asp.net mvc?,了解为什么会发生这种情况以及如何解决。
标签: c# asp.net-mvc