Add a search method and view
In this section, we will implement a SearchIndex response method that allows you to search for movies by genre or name.
It uses the URL/Movies/SearchIndex. The request will display an HTML page, which contains
Find the input control that the user inputs for a movie. When a user submits a page, the response method will get post by the user
And query the database based on the condition. The final result is as follows.
Display Search Page
First, add a SearchIndex response method to the MoviesController class. This method returns an HTML
Page View. The Code is as follows:
Public ActionResult SearchIndex (string searchString)
{
Var movies = from m in db. Movies
Select m;
If (! String. IsNullOrEmpty (searchString ))
{
Movies = movies. Where (s => s. Title. Contains (searchString ));
}
Return View (movies );
}
The first line of the SearchIndex method creates the following LINQ query to query movies:
Var movies = from m in db. Movies
Select m;
The query is defined here, but not executed! (Note: The function is executed only when it is executed.
Generally, data is actually executed only when data is actually used)
If the searchString parameter is not a null string, the query of a movie is modified to a filter string,
Use the following code:
If (! String. IsNullOrEmpty (searchString ))
{
Movies = movies. Where (s => s. Title. Contains (searchString ));
}
When it is defined or modified using the Where and OrderBy methods, the LINQ query is not executed. On the contrary,
Query execution is delayed, which means that the LINQ expression is always delayed until its real value is traversed.
Or called by the ToList method. In the SearchIndex method
View. Understanding