文章出處
文章列表
Adding Search by Genre
If you added the HttpPost
version of the Index
method, delete it now.
Next, you'll add a feature to let users search for movies by genre. Replace the Index
method with the following code:
現在我們來改寫Index方法,
1 public ActionResult Index(string movieGenre,string searchString)
2 {
3 var GenreLst = new List<string>();
4
5 var GenreQry = from d in db.Movies
6 orderby d.Genre
7 select d.Genre;
8 GenreLst.AddRange(GenreQry.Distinct());
9 //SelectList生成列表
10 ViewBag.movieGenre = new SelectList(GenreLst);
11
12 //Linq查詢
13 var movies = from m in db.Movies select m;
14
15 if (!string.IsNullOrEmpty(searchString))
16 {
17 movies = movies.Where(s => s.Title.Contains(searchString));
18 }
19 if (string.IsNullOrEmpty(movieGenre))
20 {
21 movies = movies.Where(x => x.Genre == movieGenre);
22 }
23 return View(movies);
24
25
26 }
var GenreQry = from d in db.Movies
orderby d.Genre
select d.Genre;
當執行完這句代碼之后,SQL(GenreQry)為:
1 SELECT
2 [Extent1].[Genre] AS [Genre]
3 FROM [dbo].[Movies] AS [Extent1]
4 ORDER BY [Extent1].[Genre] ASC
var movies = from m in db.Movies select m;
執行完這句代碼之后,SQL(Movies)為:
1 SELECT
2 [Extent1].[ID] AS [ID],
3 [Extent1].[Title] AS [Title],
4 [Extent1].[ReleaseDate] AS [ReleaseDate],
5 [Extent1].[Genre] AS [Genre],
6 [Extent1].[Price] AS [Price]
7 FROM [dbo].[Movies] AS [Extent1]
現在先讓我們,在Index視圖頁面中,添加一個實現下拉框的代碼吧:
In the following code:
@Html.DropDownList("movieGenre", "All")
The parameter "movieGenre" provides the key for theDropDownList
helper to find aIEnumerable<SelectListItem >
in theViewBag
. TheViewBag
was populated in the action method:
這句話的意思是:moviegenre參數,為DropDownList方法,提供了主鍵,去找到在控制器中定義的Viewbag.movieGenre
The parameter "All" provides the item in the list to be preselected. Had we used the following code:
這句話的意思是:All參數,提供了默認選擇項
效果圖:
In this section you created a search action method and view that let users search by movie title and genre. In the next section, you'll look at how to add a property to theMovie
model and how to add an initializer that will automatically create a test database.
通過下拉列表,來搜索:
通過下拉列表和title輸入框搜索:
文章列表
全站熱搜