【问题标题】:Error in Routing in ASP.NET MVCASP.NET MVC 中的路由错误
【发布时间】:2018-07-08 13:41:29
【问题描述】:

我正在尝试从列表中搜索电影。但是,搜索字符串总是返回 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 action 获取电影列表。我传递的网址是http://localhost:52872/Movies/Search/GodFather

但是,如果我将 Search 路由放在 Default 路由上方,它可以正常工作,但编辑和详细信息不起作用。

【问题讨论】:

  • 路由冲突。第一个路由模板匹配,所以它不会到达第二个。

标签: c# asp.net-mvc asp.net-mvc-routing


【解决方案1】:

路由冲突。第一个路由模板匹配,所以它不会到达第二个。

出于同样的原因,路由定义的顺序也很重要。

重构为

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 }
);

【讨论】:

    猜你喜欢
    • 2020-04-04
    • 2013-02-28
    • 2016-07-30
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    相关资源
    最近更新 更多