博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Adding Search
阅读量:5953 次
发布时间:2019-06-19

本文共 8169 字,大约阅读时间需要 27 分钟。

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

Update the Index action method to enable search:

public async Task
Index(string searchString) { var movies = _context.Movie.Select(x => x); if (string.IsNullOrEmpty(searchString) == false) { movies = movies.Where(x => x.Title.Contains(searchString)); } return View(await movies.ToListAsync()); }

上面第一行代码,还可以改为

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

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

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, using the following code:

if (string.IsNullOrEmpty(searchString) == false)            {                movies = movies.Where(x => x.Title.Contains(searchString));            }

The => x.Title.Contains() code above is a .

Lambdas are used in method-based  queries as arguments to standard query operator methods such as the  method or Contains used in the code above.

LINQ queries are not executed when they are defined or when they are modified by calling a method such as WhereContains or OrderBy.

Instead, query execution is deferred, which 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 .     //延迟加载

 

Note:

The  method is run on the database, not the c# code above.

On the database, maps to , which is case insensitive.  //不区分大小写

 

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

 

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

app.UseMvc(routes =>            {                routes.MapRoute(                    name: "default",                    template: "{controller=Home}/{action=Index}/{id?}");            });

 

You can quickly rename the searchString parameter to id with the rename command.

Right click on searchString > Rename.

Change the parameter to id and all occurrences of searchString change to id.

 

You can now pass the search title as route data (a URL segment) instead of as a query string value.

 

However, you can’t expect users to modify the URL every time they want to search for a movie.

So now you’ll add UI to help them filter movies.

If you changed the signature of the Index method to test how to pass the route-bound ID parameter, change it back so that it takes a parameter named searchString:

 

添加一个Filter进行过滤

Open the Views/Movies/Index.cshtml file, and add the <form> markup highlighted below:

@{    ViewData["Title"] = "Index";}

Index

Create New

Title:

The HTML <form> tag uses the , so when you submit the form, the filter string is posted to the Index action of the movies controller.

Save your changes and then test the filter.

 

There’s no [HttpPost] overload of the Index method as you might expect.

You don’t need it, because the method isn’t changing the state of the app, just filtering data.

You could add the following [HttpPost] Index method.

[HttpPost]public string Index(string searchString, bool notUsed){    return "From [HttpPost]Index: filter on " + searchString;}

The notUsed parameter is used to create an overload for the Index method.

We’ll talk about that later in the tutorial.

 

If you add this method, the action invoker would match the [HttpPost] Index method, and the[HttpPost] Index method would run as shown in the image below.

[HttpPost]        public string Index(string searchString, bool notUsed)        {            return "From [HttpPost]Index: filter on " + searchString;        }

这个方法添加之后,保存。然后重新刷新界面,再用ghost进行filter过滤,会出现下图

 

However, even if you add this [HttpPost] version of the Index method, there’s a limitation in how this has all been implemented.

Imagine that you want to bookmark a particular search or you want to send a link to friends that they can click in order to see the same filtered list of movies.

Notice that the URL for the HTTP POST request is the same as the URL for the GET request (localhost:xxxxx/Movies/Index) – there’s no search information in the URL.

The search string information is sent to the server as a .

You can verify that with the  or the excellent .

Start the :

 

 

You can see the search parameter and  token in the request body.

Note, as mentioned in the previous tutorial, the  generates an  anti-forgery token.

We’re not modifying data, so we don’t need to validate the token in the controller method.

 

Because the search parameter is in the request body and not the URL, you can’t capture that search information to bookmark or share with others.

We’ll fix this by specifying the request should be HTTP GET. Notice how intelliSense helps us update the markup.

Title:

Notice the distinctive font in the <form> tag. That distinctive font indicates the tag is supported by.

 

Now when you submit a search, the URL contains the search query string.

Searching will also go to the HttpGet Index action method, even if you have a HttpPost Index method.

 

 

Adding Search by Genre

Add the following MovieGenreViewModel class to the Models folder:

public class MovieGenreViewModel    {        public List
Movies; public SelectList Genres; public string MovieGenre { get; set; } }

 

The move-genre view model will contain:

  • a list of movies
  • a  containing the list of genres. This will allow the user to select a genre from the list.
  • movieGenre, which contains the selected genre

Replace the Index method with the following code:

public async Task
Index(string movieGenre,string searchString) { var movies = _context.Movie.Select(x => x); var genres = movies.Select(x => x.Genre).Distinct(); if (string.IsNullOrEmpty(searchString) == false) { movies = movies.Where(x => x.Title.Contains(searchString)); } if (string.IsNullOrEmpty(movieGenre)==false) { movies = movies.Where(x => x.Genre == movieGenre); } MovieGenreViewModel movieGenreViewModel = new MovieGenreViewModel(); movieGenreViewModel.Genres = new SelectList(await genres.ToListAsync()); movieGenreViewModel.Movies = await movies.ToListAsync(); return View(movieGenreViewModel); }

 

Adding search by genre to the Index view

@model MovieGenreViewModel@{    ViewData["Title"] = "Index";}

Index

Create New

Title:

@foreach (var item in Model.Movies) {
}
@Html.DisplayNameFor(model => model.Movies[0].Genre) @Html.DisplayNameFor(model => model.Movies[0].Price) @Html.DisplayNameFor(model => model.Movies[0].ReleaseDate) @Html.DisplayNameFor(model => model.Movies[0].Title)
@Html.DisplayFor(modelItem => item.Genre) @Html.DisplayFor(modelItem => item.Price) @Html.DisplayFor(modelItem => item.ReleaseDate) @Html.DisplayFor(modelItem => item.Title) Edit | Details | Delete

Test the app by searching by genre, by movie title, and by both.

 

转载地址:http://lkoxx.baihongyu.com/

你可能感兴趣的文章
学习 Message(11): 测试 TWMMouse 结构相关的鼠标消息
查看>>
STM32 IO口双向问题
查看>>
iOS APP删除系统相册中选中的图片
查看>>
Java资源大全中文版(Awesome最新版)
查看>>
XCode删除多余的Simulator(模拟器)
查看>>
route-policy和ACL组合时permit和deny的作用
查看>>
OSPF 特殊区域
查看>>
【EhCache】Java缓存框架使用EhCache结合Spring AOP
查看>>
MYSQL–my.cnf配置中文详解
查看>>
使用tshark监视和检查网络流量
查看>>
Linux入门之inode解析及管道重定向
查看>>
CentOS GRUB引导错误无法进入系统解决办法
查看>>
我的友情链接
查看>>
利用saltstack的api接口和modules实现实时监控
查看>>
sybase_isql命令
查看>>
kernel.sem信号量参数调优,以及ipcs信号量队列查询
查看>>
理解嵌入式开发中的一些硬件相关的概念
查看>>
ceph的读写性能测试
查看>>
access_token is invalid or not latest hint
查看>>
H3C设备之 EASY NAT
查看>>