Ajax 表单 提交到部分视图



我正在部分视图中呈现一个表单,并且还希望在那里显示结果。表单提交时没有任何反应。我知道控制器中用于查询数据库的逻辑是正确的,因为它以前作为传统的HTML表单工作。

有什么建议吗?

控制器:

public ActionResult nameSearch(DashboardViewModel model)
{
//do some stuff here; I'm certain this part works
return PartialView("_nameSearch", model);
}

部分视图:

@using (Ajax.BeginForm("nameSearch", "Dashboard", new AjaxOptions { HttpMethod = "POST" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="row form-group">
<div class="col-md-5">
@Html.LabelFor(m => m.name, new { })
@Html.TextBoxFor(m => m.name, new { @class = "form-control" })
</div>
</div>

}
<div class="row form-group">
<div class="col-md-5">
<input type="submit" class="btn btn-primary btn-block" value="Submit">
</div>
</div>
<table>
@if (IsPost)
{
foreach (var u in Model.listschools)
{
<tr>
<td>
<input type="checkbox" />&nbsp;@u.instnm<br />@u.city, @u.state<br />@u.url
</td>
</tr>
}
}
</table>

当您使用Ajax.BeginForm帮助程序将 ajaxy 行为添加到搜索中时,您应该指定UpdateTargetId,以便不显眼的 ajax 库知道应该使用 ajax 调用返回的结果更新页面的哪个部分。

此外,您可能希望返回另一个部分视图结果,该结果仅包含结果项。您可以创建另一个名为_SearchResults.chtml的分部视图。

在这里,我只是使用时间戳和搜索关键字。您可以使用呈现要显示的数据的表格表示形式的代码更新它。

<h3>@ViewBag.Title</h3>
<p>Search happened at @DateTime.Now.ToString()</p>   

现在,在您的操作方法中,您将返回此新分部视图的部分视图结果。

public ActionResult Search(string term)
{
ViewBag.Title = "Searching for : "+ term;
// Replace the above with your actual code
// which gets actual data and pass to the partial view
return PartialView("_Search");
}

在上面的例子中,我只是通过ViewBag传递一条消息。您可以通过传递项目列表(通过查询数据库生成)来替换它。

现在,在另一个视图中,在使用Ajax.BeginForm帮助程序方法时指定UpdateTargetId选项。

@using (Ajax.BeginForm("Search", "Home", new AjaxOptions { HttpMethod = "POST", 
UpdateTargetId = "searchResults" }))
{
<div class="row form-group">
<div class="col-md-5">
<label>Name</label>
<input type="text" name="term" />
</div>
</div>
}
<div id="searchResults"> </div>

当结果从服务器返回时,库将使用 Id 更新div 内的结果(由部分视图结果生成的 html 标记searchResults

最新更新