1

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. Commented Jul 8, 2018 at 13:46

1 Answer 1

1

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 }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.