[英]Live search partialview loads as full view with Ajax.BeginForm
我正在尝试使用Ajax和partialviews创建实时搜索机制。 这个想法是主视图只是一个没有提交按钮的文本框(这是程序的主要要求)。 用户在框中输入内容,然后使用onchange命令激活一个JavaScript函数,该函数将表单提交到控制器中。 然后,控制器将进行数据库搜索,并返回一个填充有结果表的局部视图,以替换原始视图中的div。
我的问题是,带有结果的partialview将作为完整视图加载到索引视图和搜索视图中。
这些是我的代码片段,从索引视图开始。
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="buscar">
@Html.Action("Buscar", "Reportes")
</div>
<div id="encontrar-form">
</div>
现在带有搜索按钮的partialview
@model IEnumerable<ProyectoTamaulipas.Reporte>
<script>
function showRes () {
document.getElementById("forma").submit();
}
</script>
<div>
<br />
<br />
<h2>Haga una búsqueda por número de folio</h2>
<p>
@using (Ajax.BeginForm("Buscar", "Reportes", FormMethod.Post, new AjaxOptions(){
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "encontrar-form"
}, new { id = "forma" }))
{
<input type="text" name="numero" onchange="showRes()" />
}
</p>
</div>
现在相关的控制器
[HttpGet]
public ActionResult Buscar()
{
return PartialView("First");
}
[HttpPost]
public PartialViewResult Buscar(string numero)
{
if (numero != null)
{
int numeroF = 0;
//var query = (from a in db.Reporte
// where SqlMethods.Like(a.Calle1, "%" + parm + "%")
// select a).ToList();
List<Reporte> query = null;
if (Int32.TryParse(numero, out numeroF))
{
query = (from a in db.Reporte
where a.Folio == numeroF
select a).ToList();
}
return PartialView("reporte", query);
}
ViewBag.Message = "no se encontraron resultados";
return PartialView("reporte");
}
最后是结果视图。
@model IEnumerable<ProyectoTamaulipas.Reporte>
@ViewBag.Message
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.UCivil_ID)
</th>
<th>
@Html.DisplayNameFor(model => model.ServicioID)
</th>
<th>
@Html.DisplayNameFor(model => model.Ubicacion)
</th>
<th>
@Html.DisplayNameFor(model => model.Calle1)
</th>
<th>
@Html.DisplayNameFor(model => model.Calle2)
</th>
<th>
@Html.DisplayNameFor(model => model.ColoniaID)
</th>
<th>
@Html.DisplayNameFor(model => model.Comentarios)
</th>
<th>
@Html.DisplayNameFor(model => model.EstatusID)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.UCivil_ID)
</td>
<td>
@Html.DisplayFor(modelItem => item.ServicioID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Ubicacion)
</td>
<td>
@Html.DisplayFor(modelItem => item.Calle1)
</td>
<td>
@Html.DisplayFor(modelItem => item.Calle2)
</td>
<td>
@Html.DisplayFor(modelItem => item.ColoniaID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Comentarios)
</td>
@*<td>
@Html.DisplayFor(modelItem => item.Fotografia)
</td>*@
<td>
@Html.DisplayFor(modelItem => item.EstatusID)
</td>
</tr>
}
</table>
我已经尝试过更改几个命令,并验证我安装的Ajax以及其他一些东西。 很抱歉,这个问题很长,但是我已经在这两个工作日里没有运气了。 谢谢您的帮助!
我通过在各个视图的布局界面上调用jquery.unobtrusive-ajax.js并更改
document.getElementById("forma").submit();
为一个
$("#forma").trigger("submit");
在搜索偏视图内名为First的搜索功能上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.