我有一些带有一些标题字段的产品列表,例如:
ID Title
1 TShirts CK
2 Brand new books
3 Selling whatever I have useless
好的,我以这种方式调用了Detail方法:
<a href='@Url.Action("Detail", "Products", new { productId = 3 })'>See detail</a>
[Route("detail/{productId:int}")]
public ViewResult Detail(int productId) {
//...
return View();
}
生成的网址为:
http:example.com/products/detail/3
嗯,我想要的是显示这样的网址:
http://example.com/products/detail/3/selling-wathever-i-have-useless
基于给定的场景,有没有一种干净利落的方法呢?
答案 0 :(得分:0)
我相信这被称为URL slug,这将使其更容易搜索。我建议你开始使用https://stackoverflow.com/a/2921135/507025来获取一个算法来帮助你 slugify 你的网址。
如果您有一个包含该信息的数据库,您可能希望将详细说明保存到该数据库中,以便在创建新项目时检查重复项。
路由将非常相似,但您需要将路由属性更改为:
[Route("detail/{productName:string")]
public ViewResult Detail(string productName)
{
return View();
}
然后,您可以在数据库中搜索详细描述以返回搜索到的项目,或者使用搜索中给出的条款返回多个结果。
这可能有不同的方法,但现在你知道它被称为“slug”&#39;您将更容易找到有关它们的信息。
答案 1 :(得分:0)
您可以使用以下路线,当您定义Url.Action
时,您可以将产品标题传递给某种转换给定text to URL
friendly text的方法。
示例强>
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{productId}/{title}",
defaults: new { controller = "Home", action = "Index", productId = UrlParameter.Optional, title = UrlParameter.Optional }
);
<a href='@Url.Action("Index", "Home", new { productId = product.ID, title = ToFriendlyUrl(product.Title) })'>See detail</a>
public ViewResult Detail(int productId, string title)
{
// ...
return View();
}
谢谢!