使用 ASP.NET MVC、jQuery 和 Ajax 请求的索引搜索过滤器






4.95/5 (26投票s)
在本文中,我们将讨论一种使用 jQuery 的 Ajax 请求来实现索引搜索过滤器的方法,基于使用 ASP.NET MVC 创建一个简单的电话簿 Web 应用程序的示例。
引言
在以下文章中,我们将演示如何为使用 ASP.NET MVC 开发的简单电话簿 Web 应用程序实现索引搜索过滤器。在讨论过程中,我们将学习如何使用 jQuery 的 AJAX 请求来动态更新电话簿列表的内容,使其能够响应用户输入。所讨论的 Web 应用程序从数据库检索电话号码列表,并根据检索到的数据生成一个网页,其中包含人员列表,这些人员的电话号码被排列成一个表格,以及一个用户可以输入他想查找的特定人员或电话号码的文本框。以下电话簿应用程序允许通过部分匹配来查找人员或电话号码。当用户在文本框字段中输入他要查找的人员或号码时,包含人员电话号码列表的表格将被修改,仅显示与搜索条件完全匹配的人员的电话号码或姓名。
使用代码
PhoneBookController.cs: 以下代码片段实现了 PhoneBookController 控制器,该控制器包含以下操作:Search 操作方法通过连接到本地数据库并执行在以下操作方法执行期间构建的 SQL 查询来检索数据。它将检索到的数据存储到数据模型中定义的列表中。另一个操作方法 Modify 用于通过执行特定的 SQL 查询将电话簿条目插入到数据库中。
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace IndexedSearch.Controllers
{
public class PhoneBookController : Controller
{
private Models.SearchModel SearchModel = new Models.SearchModel();
public ActionResult Index()
{
return View();
}
string SqlGetConnectionString(string ConfigPath, string ConnectionStringName)
{
System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(ConfigPath);
System.Configuration.ConnectionStringSettings connectionString =
rootWebConfig.ConnectionStrings.ConnectionStrings[ConnectionStringName];
if (connectionString == null || string.IsNullOrEmpty(connectionString.ConnectionString))
throw new Exception("Fatal error: Connection string is missing from web.config file");
return connectionString.ConnectionString;
}
public ActionResult Search(string text)
{
using (SqlConnection connection =
new SqlConnection(this.SqlGetConnectionString("/Web.Config", "PhoneBookDB")))
{
try
{
string SqlQuery = @"SELECT dbo.Contacts.* FROM dbo.Contacts";
if (Request.IsAjaxRequest() && text != "")
SqlQuery += " WHERE dbo.Contacts.ContactName LIKE @text OR dbo.Contacts.Phone LIKE @text";
SqlCommand command = new SqlCommand(SqlQuery, connection);
command.Parameters.AddWithValue("@text", String.Format("%{0}%", text));
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read() && reader.HasRows != false)
{
Models.PhoneBookEntry PhoneEntry = new Models.PhoneBookEntry();
PhoneEntry.ContactID = Int32.Parse(reader["ContactID"].ToString());
PhoneEntry.ContactName = reader["ContactName"].ToString();
PhoneEntry.Phone = reader["Phone"].ToString();
if ((!PhoneEntry.ContactID.Equals("")) &&
(!PhoneEntry.ContactName.Equals("")) && (!PhoneEntry.Phone.Equals("")))
SearchModel.PhoneList.Add(PhoneEntry);
}
reader.Close();
}
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
return PartialView(SearchModel.PhoneList);
}
public ActionResult Create(string person, string phone)
{
using (SqlConnection connection =
new SqlConnection(this.SqlGetConnectionString("/Web.Config", "PhoneBookDB")))
{
try
{
string SqlQuery = @"INSERT INTO dbo.Contacts VALUES (@person, @phone)";
SqlCommand command = new SqlCommand(SqlQuery, connection);
command.Parameters.AddWithValue("@person", person);
command.Parameters.AddWithValue("@phone", phone);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
return RedirectToAction("Index");
}
}
}
SearchModel.cs: SearchModel 类实例化泛型 List<T> 类,用于存储一组电话簿条目。作为参数类型 T,我们使用另一个类 _PhoneBookEntry,它表示电话簿列表的一个条目。 SearchModel 用作以下 ASP.NET MVC 项目的主要数据模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace IndexedSearch.Models
{
public class PhoneBookEntry
{
private int contact_id;
private string contact_name;
private string phone;
public int ContactID {
get { return (!contact_id.Equals(-1)) ? contact_id : -1; }
set { contact_id = (!value.Equals(-1)) ? value : -1; } }
public string ContactName {
get { return (!contact_name.Equals("")) ? contact_name : ""; }
set { contact_name = (!value.Equals("")) ? value : ""; } }
public string Phone
{
get { return (!phone.Equals("")) ? phone : ""; }
set { phone = (!value.Equals("")) ? value : ""; }
}
}
public class SearchModel
{
private List<PhoneBookEntry> phone_list = null;
public SearchModel()
{
if (phone_list == null)
phone_list = new List<PhoneBookEntry>();
}
public List<PhoneBookEntry> PhoneList
{ get { return (phone_list != null) ? phone_list : null; } }
}
}
Index.cshtml: 以下代码片段是一个包含两个表单的网页。第一个表单是 SearchForm,其中包含可编辑的文本框区域,用户可以在其中输入文本以查找与搜索条件部分匹配的电话簿条目。在以下网页的 Scripts 部分中,我们通常定义实现文本框区域事件处理的 jQuery 代码。当用户修改文本框区域时,会触发 paste/keyup 事件,以下代码通常会向特定控制器的操作调度一个 AJAX 请求,该操作从数据库检索数据并生成 HTML 内容。之后,另一个 jQuery 子句动态修改电话簿的主页。
@{
ViewBag.Title = "Index";
}
<table border="1" align="center" width="500" cellpadding="0" cellspacing="0">
@using (Html.BeginForm("SearchForm", "PhoneBookController", FormMethod.Get))
{
@Html.ValidationSummary(true);
<tr><td>
<table align="center" width="300" cellpadding="0" cellspacing="0">
<tr><td><p><b>Find a contact:</b><br />@Html.TextBox("SearchBox",
null, new { @class = "search_box", @id = "search" })</p></td></tr></table>
</td></tr>
<tr><td>
<div id="search_results">@{Html.RenderAction("Search", new { Text = "Empty" });}</div>
</td></tr>
}
@{Html.EndForm();}
<tr><td><br />
<form method="get" action=@Url.Action("Create", "PhoneBook") id="createform" autocomplete="off">
<table border="1" align="center">
<tr>
<td><b>Person:</b></td>
<td>
@Html.TextBox("Person",
null, new { @class = "person_box", @id = "person" })
</td>
</tr>
<tr><td colspan="2"><div id="invalid_person" style="color: red; visibility: hidden">Specify the correct person's name 3-31 characters</div></td></tr>
<tr>
<td><b>Phone:</b></td>
<td>
@Html.TextBox("Phone",
null, new { @class = "phone_box", @id = "phone" })
</td>
</tr>
<tr><td colspan="2"><div id="invalid_phone" style="color: red; visibility: hidden">Specify the correct phone number e.g. +x(xxx)xxx-xxxx</div></td></tr>
<tr><td colspan="2"><input type="button" id="submit_btn" value="Submit>" /></td></tr>
</table>
</form>
</td></tr>
</table>
@section Scripts {
<script type="text/javascript">
$("#person").on("keyup paste", function () {
var person_match = $("#person").val().match(/^[a-zA-Z\.\s]*$/);
var is_visible = (person_match == null) && ($("#person").val()) ? "visible" : "hidden";
$("#invalid_person").css({ 'visibility': is_visible });
});
$("#phone").on("keyup paste", function () {
var is_visible = ($("#phone").val()) && ($("#phone").val().length > 15) ||
($("#phone").val().match(/^[a-zA-Z\.\s]*$/) != null) ? "visible" : "hidden";
$("#invalid_phone").css({ 'visibility': is_visible });
});
$("#submit_btn").click(function () {
var person_match = $("#person").val().match(/^[a-zA-Z\.\s]*$/);
var phone_match = $("#phone").val.length > 0 && $("#phone").val().match(/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/);
var is_invalid_phone = (phone_match == null) || (!$("#phone").val()) || ($("#phone").val().length < 10) ? "visible" : "hidden";
var is_invalid_person = (person_match == null) && ($("#person").val()) ? "visible" : "hidden";
$("#invalid_phone").css({ 'visibility': is_invalid_phone });
if (person_match != null && phone_match != null) $("#createform").submit();
});
$("#search").on("keyup paste", function () {
$.ajax({
type: "GET",
url: '@Url.Action("Search","PhoneBook")'+"/?text="+$("#search").val(),
dataType: 'html',
contentType: 'application/html; charset=utf-8',
success: function (content, ajaxObj) {
$("#search_results").html(content);
},
});
})
</script>
}
Search.cshtml: 以下代码片段实现了一个网页,我们使用 ASP.NET 脚本语言来生成和显示从数据模型获得的电话簿条目列表。
@model List<IndexedSearch.Models.PhoneBookEntry>
<table border="0" align="center" width="500" cellpadding="0" cellspacing="0">
<tr>
<td style="text-align: center; background-color: black; color: white; width: 90px"><b>Contact ID</b></td>
<td style="text-align: left; background-color: black; color: white; width: 250px"><b>Contact Name</b></td>
<td style="text-align: center; background-color: black; color: white; width: 150px"><b>Phone</b></td>
</tr>
@{ int line_id = 0; string bgcolor = ""; }
@foreach (var PhoneBookEntry in Model)
{
<tr>
@{ bgcolor = (line_id++ % 2) == 0 ? "white" : "lightgrey"; }
<td style="background-color: @bgcolor; text-align: center; width: 90px">@line_id</td>
<td style="background-color: @bgcolor; text-align: left; width: 250px">@PhoneBookEntry.ContactName</td>
<td style="background-color: @bgcolor; text-align: center; width: 150px">@PhoneBookEntry.Phone</td>
</tr>
}
</table>
历史
- 2016 年 12 月 13 日 - 该文章的第一个版本已发布。