今天要实现根据用户名或者性别搜索用户。
1.创建一个空模板的MVC项目:
2.在App_Data文件中,添加MyDataBase数据库:
添加Employee数据表:
CREATE TABLE [dbo].[Employee] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] VARCHAR (50) NOT NULL,
[Age] INT NOT NULL,
[Gender] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
3.在Models文件夹中,使用EF设计工具由数据库生成数据模型类(DBFirst模式):
4.添加Home控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Web_SearchDemo.Models;
namespace Web_SearchDemo.Controllers
{
public class HomeController : Controller
{
MyDataBaseEntities dbe = new MyDataBaseEntities();
// GET: Home
public ActionResult Index(string search, string searchby)
{
if (searchby == "Name")//按Name查询,如果未输入直接查询,则查询所有数据
{
var employees = dbe.Employee.Where(e => e.Name.StartsWith(search) || search == null).ToList();
if (employees.Count == 0)
{//没有查询到记录
ViewBag.message = "Record Not Found";
}
return View(employees);
}
else
{//按Gender进行查询,如果未输入直接查询,则查询所有数据
var employeeList = dbe.Employee.Where(e => e.Gender == search || search == null).ToList();
if (employeeList.Count == 0)
{
ViewBag.message = "Record Not Found";
}
return View(employeeList);
}
}
}
}
}
添加对应的Index视图:
在模板视图的基础上,进行修改:
@model IEnumerable<Web_SearchDemo.Models.Employee>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
@Html.TextBox("search", null, htmlAttributes: new { @class = "form-control" })
@Html.RadioButton("searchby", "Name", true) <text>Name</text>
@Html.RadioButton("searchby", "Gender", true) <text>Gender</text>
<input type="submit" value="Search" class="btn btn-primary" />
}
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.First().Name)
</th>
<th>
@Html.DisplayNameFor(model => model.First().Age)
</th>
<th>
@Html.DisplayNameFor(model => model.First().Gender)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Gender)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
运行程序:
测试案例:
按性别搜索:
按用户名搜索: