我正在mvc5中创建搜索功能 我的程序是这样的: 索引视图具有搜索框和按钮 结果也会显示在索引视图中
所以我的问题是我如何在另一个视图中显示结果-像searchresult.cshtml这样而不在索引视图中显示?
这是我的控制器:
public ActionResult Index(string searching)
{
return View(db.TblId.Where(x => x.IdNumber.Contains(searching) || searching == null));
}
我的索引视图(我刚刚删除了其他文本内容,只包含搜索结果)
@model IEnumerable<MVC5_Search.Models.TblId>
@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
@Html.TextBox("searching")<input type="submit" value="Search" />
}
<table>
<thead>
<tr>
<td>Id Number</td>
<td>First Name</td>
<td>Middle Name</td>
<td>Last Name</td>
</tr>
</thead>
<tbody>
@if (Model.Count() == 0)
{
<tr>
<td colspan="3" style="color: red">
No Result!
</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>@item.IdNumber</td>
<td>@item.Firstname</td>
<td>@item.Middlename</td>
<td>@item.Lastname</td>
</tr>
}
}
</tbody>
</table>
我正在与实体框架一起使用
编辑:(试图解决)
这是我到目前为止所做的,
我创建了另一个控制器(SearchingController)以避免与主控制器发生冲突,
[HttpGet]
public ViewResult SearchResult(string searching)
{
return View("SearchResult", db.TblId.Where(x => x.TId.Contains(searching) || searching == null));
}
,然后查看SearchResult.cshtml
@model IEnumerable<TblId.Models.TId>
@{
ViewBag.Title = "searchresult";
}
<table>
<thead>
<tr>
<td>IdNumber</td>
<td>First Name</td>
<td>Middle Name</td>
<td>Last Name</td>
</tr>
</thead>
<tbody>
@if (Model.Count() == 0)
{
<tr>
<td colspan="3" style="color: red">
No Result!
</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>@item.IdNumber</td>
<td>@item.Firstname</td>
<td>@item.Middlename</td>
<td>@item.Lastname</td>
</tr>
}
}
</tbody>
</table>
在我的索引视图中,
@using (Html.BeginForm("SearchResult", "Searching", FormMethod.Get))
{
@*@Html.TextBox("searching")*@
<input type="text" id="searching" name="searching" />
<button type="submit" name="searching" id="searching "class="btn btn-secondary">
Verify
<br>
</button>
}
仍然无法按预期运行
当我单击搜索按钮时,它只是将网址更改为类似的内容
/ Index?searching = T101&searching =
T101-我正在搜索的ID
答案 0 :(得分:1)
请按照以下步骤操作:
->使用以下内容创建新视图searchresult.cshtml
@model IEnumerable<MVC5_Search.Models.TblId>
<table>
<thead>
<tr>
<td>Id Number</td>
<td>First Name</td>
<td>Middle Name</td>
<td>Last Name</td>
</tr>
</thead>
<tbody>
@if (Model.Count() == 0)
{
<tr>
<td colspan="3" style="color: red">
No Result!
</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>@item.IdNumber</td>
<td>@item.Firstname</td>
<td>@item.Middlename</td>
<td>@item.Lastname</td>
</tr>
}
}
</tbody>
</table>
->将索引发布操作修改为
[HttpPost]
public ViewResult Index(string searching)
{
return View("searchresult",db.TblId.Where(x => x.IdNumber.Contains(searching) || searching == null));
}