我正在寻找一种方法来返回基于Id的视图,但返回时添加友好的url部分。ASP.NET Mvc 5返回使用搜索引擎友好网址查看
我知道当我有这个数据时,我可以传入id和name,例如,通过使用:
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我想搜索的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? 设置RouteData.Values。似乎并未将该部分添加到网址中。
由于逻辑我需要做索引操作的数据库查询,但现在我需要在SelCat操作中的第二个数据库查询。该死的! 我认为这可以在一个行动中完成。 – juFo
鉴于您是通过id查询的,任何像样的数据库都应该可以正常查询主键。另外,如果您担心性能,可以添加一些缓存层。 –