我正在尋找一種方法來返回基於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查詢的,任何像樣的數據庫都應該可以正常查詢主鍵。另外,如果您擔心性能,可以添加一些緩存層。 –