我有一个可以搜索记录的视图。
@using (Html.BeginForm("Index", "Project", FormMethod.Get, new { role = "form" }))
{
<div class="input-group">
<input name="Query" type="text" class="form-control" placeholder="">
<span class="input-group-btn" style="width:0;">
<button class="btn btn-default" type="submit">Search</button>
</span>
</div>
}
@if (Model.Any())
{
<div class="col-md-10">
<table class="table table-striped table-hover">
<tr>
<th>
Year
</th>
<th>
Project
</th>
<th>
Status
</th>
<th>
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(m => item.PROJ_YEAR)
</td>
<td>
@Html.DisplayFor(m => item.PROJ_NAME)
</td>
<td>
@Html.DisplayFor(m => item.PROJ_STATUS)
</td>
</tr>
}
</table>}
else
{
<p style="margin:20px 0;">No Projects found.</p>
}
这是控制器
public ActionResult Index(int page = 1, string Query = null)
{
var projectList = db.TBL_PROJECTS.Include(x => x.TBL_STATUS).Where(x => x.PROJ_CAT == 1).ToList().OrderByDescending(x => x.ID);
if (!string.IsNullOrEmpty(Query))
{
projectList = projectList
.Where(x => x.PROJ_NAME.ToLower().Contains(Query.ToLower()))
.ToList().OrderByDescending(x => x.ID);
if (projectList.Count() == 0)
{
var list = db.TBL_PROJECTS.Include(x => x.TBL_STATUS).Where(x => x.PROJ_CAT == 1).ToList().OrderByDescending(x => x.ID);
projectList = list
.Where(x => x.PROJ_YEAR.ToLower().Contains(Query.ToLower()))
.ToList().OrderByDescending(x => x.ID);
}
}
return View(new PagedList.PagedList<TBL_PROJECT>(projectList, page, 15));
}
执行搜索时,它只会根据PROJ_NAME执行搜索。 我想通过&#34; PROJ_YEAR&#34;太。当我搜索&#34; 1998&#34;时,将找不到记录。当我搜索&#34; Paint Job&#34;在1998年,将显示记录。
答案 0 :(得分:0)
projectList = projectList
.Where(x => x.PROJ_NAME.ToLower().Contains(Query.ToLower())
|| x.PROJ_YEAR = Int32.Parse(Query) )
.ToList().OrderByDescending(x => x.ID);
或使用Int32.TryParse()
答案 1 :(得分:0)
因为您只比较项目名称列。因此,当您提交年份时它不起作用。您应该修改控制器,例如:
public ActionResult Index(int page = 1, string Query = null)
{
var projectList = db.TBL_PROJECTS.Include(x => x.TBL_STATUS).Where(x => x.PROJ_CAT == 1).ToList().OrderByDescending(x => x.ID);
if (!string.IsNullOrEmpty(Query))
{
projectList = projectList
.Where(x => x.PROJ_NAME.ToLower().Contains(Query.ToLower())
|| x.PROJ_YEAR.ToLower().Contains(Query.ToLower()))
.ToList().OrderByDescending(x => x.ID);
}
return View(new PagedList.PagedList<TBL_PROJECT>(projectList, page, 15));
}
答案 2 :(得分:0)
找到答案。对于稍后遇到此类问题的人来说,这可能会有用。这就是我做到的。
if (!string.IsNullOrEmpty(Query))
{
projectList = projectList
.Where(x => x.PROJ_NAME.ToLower().Contains(Query.ToLower()))
.ToList().OrderByDescending(x => x.ID);
if (projectList.Count() == 0)
{
var list = db.TBL_PROJECTS.Include(x => x.TBL_STATUS).Where(x => x.PROJ_CAT == 1).ToList().OrderByDescending(x => x.ID);
var k = list
.Where(x => x.PROJ_YEAR != null)
.ToList().OrderByDescending(x => x.ID);
projectList = k
.Where(x => x.PROJ_YEAR.ToLower().Contains(Query.ToLower()))
.ToList().OrderByDescending(x => x.ID);
}