https://docs.asp.net/en/latest/tutorials/first-mvc-app/search.html

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<IActionResult> 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 LINQ 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 => x.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 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 Query Execution.     //延迟加载

Note:

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

On the database, Containsmaps to SQL LIKE, 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";
} <h2>Index</h2> <p>
<a asp-action="Create">Create New</a>
</p> <form asp-controller="Movies" asp-action="Index">
<p>
Title: <input type="text" name="SearchString">
<input type="submit" value="Filter" />
</p>
</form> <table class="table">

The HTML <form> tag uses the Form Tag Helper, 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 form field value.

You can verify that with the F12 Developer tools or the excellent Fiddler tool.

Start the F12 tool:

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

Note, as mentioned in the previous tutorial, the Form Tag Helper generates an XSRF 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.

<form asp-controller="Movies" asp-action="Index" method="get">
<p>
Title: <input type="text" name="SearchString">
<input type="submit" value="Filter"/>
</p>
</form>

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

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<Movie> Movies; public SelectList Genres; public string MovieGenre { get; set; }
}

The move-genre view model will contain:

  • a list of movies
  • SelectList 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<IActionResult> 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";
} <h2>Index</h2> <p>
<a asp-action="Create">Create New</a>
</p> <form asp-controller="Movies" asp-action="Index" method="get">
<p>
<select asp-for="MovieGenre" asp-items="Model.Genres">
<option value="">All</option>
</select> Title: <input type="text" name="SearchString">
<input type="submit" value="Filter" />
</p>
</form> <table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Movies[0].Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.Movies[0].Price)
</th>
<th>
@Html.DisplayNameFor(model => model.Movies[0].ReleaseDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Movies[0].Title)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Movies)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.ID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
</td>
</tr>
}
</tbody>
</table>

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

Adding Search的更多相关文章

  1. 011.Adding Search to an ASP.NET Core MVC app --【给程序添加搜索功能】

    Adding Search to an ASP.NET Core MVC app 给程序添加搜索功能 2017-3-7 7 分钟阅读时长 作者 本文内容 1.Adding Search by genr ...

  2. ASP.NET Core 中文文档 第二章 指南(4.7)添加搜索

    原文:Adding Search 作者:Rick Anderson 翻译:魏美娟(初见) 校对:谢炀(Kiler) .孟帅洋(书缘).张仁建(第二年.夏) 在本节中,你可以为 Index 方法添加查询 ...

  3. IOS 开发教程

    http://www.raywenderlich.com/category/ios http://www.raywenderlich.com/50310/storyboards-tutorial-in ...

  4. ASP.NEt MVC5--创建下拉列表

    Adding Search by Genre If you added the HttpPost version of the Index  method, delete it now. Next, ...

  5. Using ASP.Net WebAPI with Web Forms

    Asp.Net WebAPI is a framework for building RESTful HTTP services which can be used across a wide ran ...

  6. 004.Create a web app with ASP.NET Core MVC using Visual Studio on Windows --【在 windows上用VS创建mvc web app】

    Create a web app with ASP.NET Core MVC using Visual Studio on Windows 在 windows上用VS创建mvc web app 201 ...

  7. Android Training

    Building Apps with Content Sharing Simple Data --> Intent && ActionProvider 介绍如何让应用程序共享简单 ...

  8. CDN:分类

    ylbtech-CDN:分类 1.返回顶部 1. bootstrap Bootstrap 是全球最受欢迎的前端组件库,用于开发响应式布局.移动设备优先的 WEB 项目. 2. feather-icon ...

  9. [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

随机推荐

  1. SQL Server跨库跨服务器访问实现

    我们经常会遇到一个数据库要访问另一个数据库,或者一台服务器要访问另一台服务器里面的数据库. 那么这个如何实现的呢? 相信看完这篇文章你就懂了! 同一台服务器跨库访问实现 1. 首先创建两个数据库Cro ...

  2. Beta冲刺-星期三

    这个作业属于哪个课程  <课程的链接>            这个作业要求在哪里 <作业要求的链接> 团队名称 Three cobblers 这个作业的目标 剩余任务预估,分配 ...

  3. 后端springmvc,前端html5的FormData实现文件断点上传

    前言 最近项目中有使用到文件断点上传,得空便总结总结,顺便记录一下,毕竟“好记性不如烂笔头”. 后端代码: package com.test.controller; import java.io.Bu ...

  4. 查找索引/ie滤镜/动态背景/属性attr和prop

    1. 查找索引 查找当前元素在指定范围内的索引序号,示例: $('.right_newestState_con').find('em').index($(this)); 2. ie滤镜 利用ie的私有 ...

  5. 安卓学习之学生签到APP(一)

    一.学生定位签到页面 具体实现步骤: 1.1 高德地图申请key 1.创建新应用 进入高德地图api控制台,创建一个新应用.如果您之前已经创建过应用,可直接跳过这个步骤. 2.添加新Key 在创建的应 ...

  6. AI:IPPR的数学表示-CNN可视化语义分析

    前言: ANN是个语义黑箱的意思是没有通用明确的函数表示,参数化的模型并不能给出函数的形式,更进而不能表示函数的实际意义. 而CNN在图像处理方面具有天然的理论优势,而Conv层和Polling层,整 ...

  7. PCL: 根据几何规则的曲面剖分-贪婪法表面重建三角网格

    点云场景中进行物体识别,使用全局特征的方法严重依赖于点云分割,难以适应杂乱场景.使用局部特征,即对点云进行提取类似于3D SURF.ROPS之类的局部特征,需要寻找离散点云块的局部显著性. 点云的基本 ...

  8. AdaBoost--从原理到实现(Code:Python)

    本文对原文有修改,若有疑虑,请移步原作者.  原文链接:blog.csdn.net/dark_scope/article/details/14103983 集成方法在函数模型上等价于一个多层神经网络, ...

  9. mount 命令总结

    配置CnetOS 7.4 本地yum源,记录下遇到的ISO镜像挂载问题,使用 blkid 命令可以查看设备的UUID.Label.文件系统类型(iso镜像文件系统类型iso9660) [root@lo ...

  10. bzoj4320 homework 题解

    题面链接:https://www.lydsy.com/JudgeOnline/problem.php?id=4320 令M=sqrt(mx),把询问的Y按M 分成两种不同的处理方式. 1.对于> ...