我有一个简单的 Wall.cshtml View ,它加载一个 _Search.cshtml 部分 View ,如下所示:
<h2>The Wall</h2>
@{Html.RenderPartial("~/Views/Search/_Search.cshtml");}
_Search.cshtml 部分 View (根据@Darin 回复更新)如下所示:
@using (Html.BeginForm("Searching", "Search", FormMethod.Post, new { id = "searchForm" }))
{
<div id="search">
<div id="searchbtn">
<input id="Search" type="button" value="Search" />
</div>
<div id="searchtxt">
@Html.TextBox("txtSearch")
</div>
</div>
}
Controller 看起来像这样:
public class SearchController : Controller
{
public ActionResult Wall()
{
return View();
}
[HttpPost]
public ActionResult Searching()
{
// do something with the search value
return View();
}
}
当我运行应用程序时,生成的 HTML block 如下所示:
<form action="/Search/Searching" id="searchForm" method="post">
<div id="search">
<div id="searchbtn">
<input id="Search" type="button" value="Search" />
</div>
<div id="searchtxt">
<input id="txtSearch" name="txtSearch" type="text" value="" />
</div>
</div>
</form>
问题 1:为什么单击按钮永远不会命中搜索 Controller 方法?
(让我重申一下,_Search.cshtml 是一个在名为 Wall.cshtml 的 View 内运行的部分 View )。
问题 2:如何获取“txtSearch”文本框中的值?
问题 3:由于这是一个部分 View ,我如何使包含当前搜索部分 View 的 View ..使用搜索查询的结果刷新和更新自身?
最佳答案
最好使用表单并使搜索按钮提交:
@using (Html.BeginForm("Search", "Home", FormMethod.Post, new { id = "searchForm" }))
{
<div id="search">
<div id="searchbtn">
<input id="Search" type="submit" value="Search" />
</div>
<div id="searchtxt">
@Html.TextBox("txtSearch")
</div>
</div>
}
就您的第二个问题而言,您可以 AJAX 化此搜索表单:
$(function() {
$('#searchForm').submit(function() {
$.ajax({
url: this.action,
type: this.method,
success: function(result) {
$('#resultContainer').html(result);
}
});
return false;
});
});
其中 resultContainer
可以是某个 div,它将保存从 Controller 操作返回的搜索结果。
关于asp.net-mvc-3 - MVC 3 (Razor) - 使用按钮事件调用 Controller 的标准方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5561546/