Julian と同様の状況: MVC - クエリ文字列を使用したルート
フォームから定義されたルートと値を使用して、GET リクエストを使用してフォームを操作する方法を把握できません。
(編集:ジュリアンの問題と本質的に同じコンテキストですが、javascriptライブラリやカスタムルーティングの観点から特定の解決策について尋ねます(一般的な領域ではなく、特定のコードに問題と異なるアプローチが必要な理由を説明するのではなく) ; また、global.asaxを使用していない; 質問から 1 年以上経過しているということは、他のオプションも利用できる可能性があることを意味します。)
初心者の場合、クライアント ライブラリが圧倒的に多く、関連するカスタム ルート プロバイダーをどこから始めればよいかほとんどわからないため、先に進むのは困難ですが、サーバー側のルーティングと 301 リダイレクトを維持するシンプルさのためには、これがより望ましいようです。
さまざまなルート(明らかに「カスタム」ではない)を試し、多くのライブラリを調べましたが、具体的な進歩はありませんでした。
ルーティングの例/キーワード/リンク、単純なクライアント コードの例 (このコンテキストなど) などの単純なポインターは非常に役立ちます。
このチュートリアルを使用して、タイトルとジャンルによる映画の検索ページを作成します。]
ここに私の特定のコードがあります:
ルート構成:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Movies",
url: "{controller}/{action}/{title}/{genre}",
defaults: new
{
controller = "Home",
action = "Index"
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
}
アクション結果:
public ActionResult SearchIndex(string title, string genre)
{
var genreQuery = from g in db.Movies
orderby g.Genre
select g.Genre;
var genres = new List<string>();
genres.AddRange(genreQuery.Distinct());
ViewBag.Genre = new SelectList(genres);
var movies = from m in db.Movies
select m;
if (!string.IsNullOrEmpty(title))
{
movies = movies.Where(s => s.Title.Contains(title));
}
if (!string.IsNullOrEmpty(genre))
{
movies = movies.Where(s => s.Genre == genre);
}
return View(movies);
}
SearchIndex.cshtml:
@model IEnumerable<DefaultMvcIA.Models.Movie>
@{
ViewBag.Title = "SearchIndex";
}
<h2>SearchIndex</h2>
<p>
@Html.ActionLink("Create New", "Create")
@using (Html.BeginForm("SearchIndex", "Movies", FormMethod.Get))
{
<p>Genre: @Html.DropDownList("Genre", "All")
Title: @Html.TextBox("Title")<br />
<input type="submit" value="Filter" /></p>
}
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.ReleaseDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.MovieID }) |
@Html.ActionLink("Details", "Details", new { id=item.MovieID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.MovieID })
</td>
</tr>
}
</table>
問題 GET 要求では、ブラウザーはクエリ文字列を使用するだけで、RouteConfig でルーティングを設定しません (当然のことです)。これらのクエリ文字列をルーティングするか、クライアント ライブラリを使用するようにリダイレクトするには、カスタム ルートを記述する必要があります。多くの異なるルーティング ライブラリがあり、(望ましい) 301 カスタム ルーティング メソッドをどこから始めればよいかわからないため、特定の情報は非常に役立ちます。