[英]Changing the generated details view in mvc
所以我有一个名为Movies的Views文件夹。 我里面有索引,创建,删除,详细信息,编辑。 (自动生成)。 现在,当我单击详细信息按钮时,URL变为xx.com/Movies/Details/2。 该数字表示数据库中的ID。 有没有办法显示标题而不是ID?
当然是。 您只需要更新路线。 在您的Route Config文件中,您会注意到这样的一行:
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
在这里,您需要将其更改为
routes.MapRoute("Default", "{controller}/{action}/{title}", new { controller = "Home", action = "Index", title = UrlParameter.Optional });
现在,您应该将操作方法签名从
public ActionResult Details(int id)
{
return View();
}
至
public ActionResult Details(string title)
{
return View();
}
顺便说一句,我没有测试它,我只是写出了概念。 您需要进行测试,特别是如果您的标题不是url编码或包含无破折号的空格时。
编辑:
在MVC 5中,可以使用基于属性的路由。
我用它来生成像这样的SEO URL:
[Route("Products/{slug}-{productId}")]
public ActionResult Details(int productId, string slug)
{
return View();
}
当我需要创建网址时,我使用了snippet:
Url.Action("Details", "Products", new { productId = 201, slug = "My-Keyword-Title" })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.