私はIdに基づいてビューを返す方法を探していますが、返すときはフレンドリーなURL部分を追加します。ASP.NET Mvc 5戻り値親しみやすい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 });
}
は場合、私は、ビューを返すとき、私はseofriendly名前を検索すると、唯一のIDでindexアクションにSelCatアクションからリダイレクトします。私は、そのURLに友好的なURLの部分があることを望んでいました。唯一のIDが与えられたとき、私のコントローラのアクションでビューを返すとき
// 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
}
は、どのように私は私のURLのSEOは友好することができますか? RouteData.Valuesを設定します。その部分を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
アクションに達したら:あなたがリダイレクトする前にSEOフレンドリースラグのためにデータベースに見ていると、URLに含め、それ以外の場合は、手遅れになる
インデックスアクションでデータベースクエリを実行する必要があるため、今ではSelCatアクションで2番目のデータベースクエリが必要になります。畜生! 私はそれが1つのアクションで実行できると思いました。 – juFo
IDで照会しているとすれば、適切なデータベースは主キーで照会するだけで十分です。さらに、パフォーマンスが気になる場合は、キャッシングレイヤーを追加することもできます。 –