MVC - 路线与查询字符串 [英] MVC - Route with querystring
问题描述
以下后,<一个href=\"http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc-4-and-visual-studio-2011/examining-the-details-and-delete-methods\"相对=nofollow>这个的MVC 4教程系列,我想有些东西我自己。
我开始试图使searchfilter URL友好。下面code是我目前使用的是什么:
After following this MVC 4 tutorial series I was trying some of the stuff myself. I started by trying to make the searchfilter url friendly. The following code is what I'm using at the moment:
的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));
}
}
现在一切顺利,当我把下面的网址在我adressbar: /电影/ SearchIndex /喜剧/福尔摩斯
Now everything goes well when I put the following url in my adressbar: /Movies/SearchIndex/Comedy/Sherlock
但是,当我用过滤器按钮,在SearchIndex.cshtml我得到以下URL过滤: /电影/ SearchIndex movieGenre =喜剧和放大器;搜索字符串=福尔摩斯
But when I filter with the "filter" button in the SearchIndex.cshtml I get the following url: /Movies/SearchIndex?movieGenre=Comedy&searchString=Sherlock
这里有人知道这个问题的?
Anyone knows the problem here?
推荐答案
当您使用形式方法=获取,你的浏览器将加入您的表单字段连成一个长的查询字符串。这有没有关系MVC本身。一对夫妇的解决方案:
When you use form method="get", your browser will join your form fields together into a long querystring. This has nothing to do with MVC itself. A couple of solutions:
- 处理表单提交事件的客户端,并且您认为合适的重新创建的URL。
- 创建了301查询字符串的重定向到一个友好URL的自定义路由提供商。
这篇关于MVC - 路线与查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!