【问题标题】:MVC URL Rewrite by using custom field使用自定义字段重写 MVC URL
【发布时间】:2016-04-18 00:29:47
【问题描述】:

我有一个 MVC 5 项目,其模型名为 ProductModel,控制器名为 ProductController。 我还有一个带有字段标题的产品数据行:Canon DSLR Cameras 默认情况下,当用户想要查看产品详情时,他们会看到 url http://../Product/Details/1

我们可以将网址更改为:http://../Product/Canon-DSLR-Cameras 吗?

谢谢。

【问题讨论】:

  • 你有没有尝试过?也许有路线?
  • 我尝试使用“MVC URL Rewrite”等关键字找到解决方案。但他们无法解决。

标签: asp.net-mvc


【解决方案1】:

在您的 RouteConfig.cs 中

您可以像这样简单地添加路线图:

routes.MapRoute("Details", "Product/{customUrl}",
       new { controller = "Product", action = "Details" },
       new { customUrl = @"\S+" } );

并编写一个控制器动作(ProductController.cs):

public ActionResult Details(string customUrl)
{
   // find ProductModel by customUrl
   ...
   return View(); // pass the model matching customUrl
}

【讨论】:

  • 谢谢。这个对我有用。在其他情况下,我的网站将使用英语和西班牙语。那么,我们可以将链接更改为 http://../producto/。同时继续使用 ProductController ?
  • @MrStone 请参考这个问题的答案stackoverflow.com/questions/4271769/…
猜你喜欢
  • 2014-06-25
  • 2014-04-11
  • 1970-01-01
  • 2018-08-14
  • 1970-01-01
  • 2011-12-14
  • 2012-08-02
  • 2016-05-13
  • 2020-09-03
相关资源
最近更新 更多