AspNetCore.Docs/aspnetcore/includes/mvc-intro/search1.md

2.8 KiB

Add search to an ASP.NET Core MVC app

By Rick Anderson

In this section you add search capability to the Index action method that lets you search movies by genre or name.

Update the Index method with the following code:

[!code-csharp]

The first line of the Index action method creates a LINQ query to select the movies:

var movies = from m in _context.Movie
             select m;

The query is only defined at this point, it has not been run against the database.

If the searchString parameter contains a string, the movies query is modified to filter on the value of the search string:

[!code-csharp]

The s => s.Title.Contains() code above is a Lambda Expression. Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as the Where method or Contains (used in the code above). LINQ queries are not executed when they're defined or when they're modified by calling a method such as Where, Contains or OrderBy. Rather, query execution is deferred. That means that the evaluation of an expression is delayed until its realized value is actually iterated over or the ToListAsync method is called. For more information about deferred query execution, see Query Execution.

Note: The Contains method is run on the database, not in the c# code shown above. The case sensitivity on the query depends on the database and the collation. On SQL Server, Contains maps to SQL LIKE, which is case insensitive. In SQLite, with the default collation, it's case sensitive.

Navigate to /Movies/Index. Append a query string such as ?searchString=Ghost to the URL. The filtered movies are displayed.

Index view

If you change the signature of the Index method to have a parameter named id, the id parameter will match the optional {id} placeholder for the default routes set in Startup.cs.

[!code-csharp]