1
votes

I am trying to search a movie from a list. However, the search string always returns null.

My Controller Code

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

Routing Configuration

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

I am able to get the list of movies from Index action. The URL I am passing is http://localhost:52872/Movies/Search/GodFather

However if I place my Search route above the Default route, it works fine, but the edit, and details does not work.

1
Route conflict. first route template matches so it does not reach the second one. - Nkosi

1 Answers

1
votes

Route conflict. First route template matches so it does not reach the second one.

Order of route definition is also important for the same reason.

Refactor to

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