ASP.NET Mvc 5 返回带有 seo 友好 url 的 View

标签 asp.net asp.net-mvc seo asp.net-mvc-routing

我正在寻找一种基于 Id 返回 View 的方法,但在返回时添加友好的 url 部分。

我知道当我有可用的数据时,我可以传入 ID 和名称,例如通过使用:

Url.Action("Index", "Cat", new { id = model.ID, seoname = model.SEO });


[AllowAnonymous]
[Route("Cat/{id?}/{seoname?}")]
public ActionResult Index(int? id = null, string seoname = null) {
   // do something with id and create viewmodel 

   // in case I get redirect from the SelCat actionresult:
   if (id.HasValue and string.IsNullOrEmpty(seoname)) { 
      // look in the database for title by the given id
      string seofriendlyTitle = ...;
      RouteData.Values.AddOrSet("seoname", seofriendlyTitle);
   }

   return View(viewmodel);
}

上面这段代码没有问题。当我提交只有可用 ID 的表单(下拉列表)时会出现问题。

[HttpPost]
[AllowAnonymous]
[Route("Cat/SelCat/{form?}")]
public ActionResult SelCat(FormCollection form) 
{ 
   string selectedValues = form["SelectedCat"];
   // ...
   int id = selectedCatID;
   return RedirectToAction("Index", new { id = id });
} 

如果我从 SelCat 操作重定向到仅具有 ID 的 Index 操作,我想在返回 View 时搜索 seofriendly 名称。我希望该网址具有友好的网址部分。

   // in case I get redirect from the SelCat actionresult:
   if (id.HasValue and string.IsNullOrEmpty(seoname)) { 
      // look in the database for title by the given id
      string seofriendlyTitle = ...;
      RouteData.Values.AddOrSet("seoname", seofriendlyTitle); // <-- does not alter url
   }

在仅提供 ID 的情况下,如何在我的 Controller 操作中返回 View 时使我的 url seo 友好? 设置 RouteData.Values。似乎没有将部分添加到 url。

最佳答案

您必须在重定向之前在数据库中查找对 SEO 友好的 slug,并将其包含在 url 中,否则为时已​​晚:

[HttpPost]
[AllowAnonymous]
[Route("Cat/SelCat/{form?}")]
public ActionResult SelCat(FormCollection form) 
{ 
    string selectedValues = form["SelectedCat"];
    // ...
    int id = selectedCatID;

    // look in the database for title by the given id
    string seofriendlyTitle = ...;
    return RedirectToAction("Index", new { id = id, seoname = seofriendlyTitle });
}

一旦您到达Index 操作,就无法更改客户端上显示的 url 已经太晚了,除非您进行额外的重定向(这当然是疯狂的) .

关于ASP.NET Mvc 5 返回带有 seo 友好 url 的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41724206/

相关文章:

css - WP 移动样式 css 与 wp_head 功能

php - 如何更改 cakephp 中的分页 url 以获得更好的 seo

javascript - 根据 true 或 false word 更改表列的颜色

asp.net-mvc - ASP.NET MVC - 从 URL 中删除 Controller 名称

c# - SQL 查询没有获取所有数据 C#/ASP.net

asp.net-mvc - Elmah 不会在 MVC 应用程序中记录 http post 请求的异常 - 如果请求包含 XML

c# - 在 gridview 中使用 PAGING 为 FILTER 实现正确逻辑的方法

php - 语言重定向的 HTTP 状态码

c# - 如何创建日历事件。带有预填收件人电子邮件的 ics?

javascript - Ajax 调用总是返回错误 500 客户端