[英]Loading partial view into div only works once
我有以下控制器并查看:
SearchController.cs :
public class SearchController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult SearchResults()
{
int rnd = new Random().Next(100);
var model = new List<SearchResultModel>
{
new SearchResultModel { Id=rnd, FirstName="Peter" + rnd, Surname="Pan" },
new SearchResultModel { Id=rnd+1, FirstName="Jane", Surname="Doe"+rnd }
};
return PartialView("SearchResults", model);
}
}
Index.cshtml :
@model WebApplication1.Models.SearchCriterionModel
@{
ViewBag.Title = "Index";
}
<script type="text/javascript">
$(document).ready(function () {
$('#btnSearch').click(function (evt) {
evt.preventDefault();
$('#placeholder').load("/Search/SearchResults");
})
});
</script>
<button id="btnSearch">Search</button>
<div id="placeholder"></div>
我只是发现我用于视图的模板(标准的Edit模板)插入了Html.BeginForm
,以某种方式不允许我将局部视图填充到div
。 因此,我消除了混乱,并尝试了“从头开始”,然后看-确实可行。 现在,我可以使用id = placeholder
将局部视图SearchResults
成功加载到div
。
但是:这仅适用一次。 也就是说,在第一次单击按钮时,将调用代码隐藏方法SearchResults()
,并且div
中将填充第一组“随机”数据。 单击不止一次会进入客户端click方法,但是不再进入我的SearchResults()
方法,所以我想没有回发发生了! 为什么会这样? 我该如何“修复”此问题,也就是说,学会如何正确执行此操作并在每次按下按钮时获取新数据?
我的MVC有点生锈,但是您可以尝试向URL添加一个随机数,这样浏览器就不会从缓存中获取它。 不知道控制器方法是否会忽略'r'参数。
<script type="text/javascript">
$(document).ready(function () {
$('#btnSearch').click(function (evt) {
evt.preventDefault();
var random = getRandomNumber(); //TODO: implement
$('#placeholder').load("/Search/SearchResults?r=" + random);
})
});
</script>
出于完成的目的,这就是我最终这样做的方式。
首先,我使用了一个表单,因为我想将参数传递给控制器中的action方法,类似于:
@using(Html.BeginForm())
{
.
.
some input elements
.
.
<input type="submit" value="Search" />
}
然后,我使用了以下脚本。 请注意,要使此方法起作用,现在,动作方法还必须将ViewModel的实例作为参数。
<script type="text/javascript">
$(document).ready(function () {
$("form").submit(function () {
var model = $(this).serialize();
$.ajax({
url: '@Url.Action("SearchResults", "Search")',
data: model,
cache: false,
dataType: "html",
success: function (response) {
$("#placeholder").html(response);
}
});
return false;
})
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.