ASP.NET MVC 中的路由错误
Error in Routing in ASP.NET MVC
我正在尝试从列表中搜索电影。但是,搜索字符串总是 returns null.
我的控制器代码
public ActionResult Index()
{
return View(db.Movies.ToList());
}
public ActionResult Search(string searchstring)
{
var movies = from m in db.Movies
where m.Title.Contains(searchstring)
select m;
return View(movies.ToList());
}
// GET: Movies/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return HttpNotFound();
}
return View(movie);
}
路由配置
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Movies", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Search",
url: "{controller}/{action}/{searchstring}"
);
我可以从 Index
操作中获取电影列表。我传递的 URL 是 http://localhost:52872/Movies/Search/GodFather
然而,如果我将我的 Search
路线放在 Default
路线之上,它工作正常,但编辑和细节不起作用。
路线冲突。第一个路由模板匹配,因此它不会到达第二个。
出于同样的原因,路由定义的顺序也很重要。
重构为
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Search",
url: "Movies/Search/{searchstring}",
defaults: new { controller = "Movies", action = "Search"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Movies", action = "Index", id = UrlParameter.Optional }
);
我正在尝试从列表中搜索电影。但是,搜索字符串总是 returns null.
我的控制器代码
public ActionResult Index()
{
return View(db.Movies.ToList());
}
public ActionResult Search(string searchstring)
{
var movies = from m in db.Movies
where m.Title.Contains(searchstring)
select m;
return View(movies.ToList());
}
// GET: Movies/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Movie movie = db.Movies.Find(id);
if (movie == null)
{
return HttpNotFound();
}
return View(movie);
}
路由配置
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Movies", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Search",
url: "{controller}/{action}/{searchstring}"
);
我可以从 Index
操作中获取电影列表。我传递的 URL 是 http://localhost:52872/Movies/Search/GodFather
然而,如果我将我的 Search
路线放在 Default
路线之上,它工作正常,但编辑和细节不起作用。
路线冲突。第一个路由模板匹配,因此它不会到达第二个。
出于同样的原因,路由定义的顺序也很重要。
重构为
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Search",
url: "Movies/Search/{searchstring}",
defaults: new { controller = "Movies", action = "Search"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Movies", action = "Index", id = UrlParameter.Optional }
);