在关注this MVC 4教程系列后,我自己尝试了一些东西。 我开始尝试使searchfilter网址友好。以下代码是我目前正在使用的代码:
Global.asax中
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
name: "MovieSearch",
url: "Movies/SearchIndex/{movieGenre}/{searchString}",
defaults: new { controller = "Movies", action = "SearchIndex", movieGenre = UrlParameter.Optional, searchString = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
SearchIndex.cshtml
<p>
@Html.ActionLink("Create New", "Create")
@using (Html.BeginForm("SearchIndex", "Movies", FormMethod.Get))
{
<p> Genre: @Html.DropDownList("movieGenre", "All")
Title: @Html.TextBox("searchString")<br />
<input type="submit" value="Filter" /></p>
}
</p>
MoviesController.cs
//
// GET: /Movies/SearchIndex/Comedy/Sherlock
public ActionResult SearchIndex(string movieGenre, string searchString)
{
var GenreList = new List<string>();
var GenreQry = from d in db.Movies
orderby d.Genre
select d.Genre;
GenreList.AddRange(GenreQry.Distinct());
ViewBag.movieGenre = new SelectList(GenreList);
var movies = from m in db.Movies
select m;
if (!string.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
if (string.IsNullOrEmpty(movieGenre))
{
return View(movies);
}
else
{
return View(movies.Where(m => m.Genre == movieGenre));
}
}
现在,当我将以下网址放入我的地址栏时一切顺利: / Movies / SearchIndex / Comedy / Sherlock
但是当我使用SearchIndex.cshtml中的“过滤器”按钮进行过滤时,我得到以下网址: / Movies / SearchIndex?movieGenre = Comedy&amp; searchString = Sherlock
有人知道这里的问题吗?
答案 0 :(得分:2)
当您使用form method =“get”时,您的浏览器会将表单字段连接到一个长查询字符串中。这与MVC本身无关。几个解决方案:
答案 1 :(得分:1)
路由由ASP.NET MVC在服务器端生成:当您按下过滤器按钮时,浏览器正在创建GET请求:它不知道路由,因此它使用查询字符串格式。