我正在寻找一种基于 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/