[英]Partial View content is not reloaded
我有一个带有按钮的视图,单击此按钮时,Ajax函数将调用控制器方法ApplicationAndUse,该方法应将列表传递给包含在我的视图中的部分视图。 应该刷新部分视图的内容,但这不起作用,我的部分仍然是空的。 我的代码:
主视图:
@model List<String>
<div class="row">
<div class="col-md-2">
@foreach (var item in Model)
{
<div id="univers-@item" class="btn btn-info">@item</div><br />
}
</div>
<div class="col-md-10">
@Html.Partial("_ApplicationAndUsePartial", null, new ViewDataDictionary())
</div>
</div>
@section scripts
{
<script type="text/javascript">
$(function () {
$('[id^=univers]').click(function () {
var selectedButton = $(this).attr('id');
var selectedUniverse = selectedButton.substring(selectedButton.indexOf('-') + 1, selectedButton.lenght);
$.ajax({
url: "http://" + window.location.host + "/UseAndNeed/ApplicationAndUse",
type: "POST",
data: { idUniverse: selectedUniverse },
dataType: "json",
});
});
});
</script>
}
部分视图:
@model List<int>
@if (Model!= null) {
foreach (var item in Model)
{
<div id="ApplicationUse-@item" class="btn btn-default">@item</div><br />
}
}
控制器功能:
[OutputCache(Duration = 0)]
public ActionResult ApplicationAndUse(String idUniverse)
{
List<int> items = new List<int>();
items.Add(1);
items.Add(2);
return PartialView("_ApplicationAndUsePartial", (object)items);
}
我想念什么?
为要显示部分视图内容的div指定一个唯一的ID。
<div id="myPartial" class="col-md-10">
@Html.Partial("_ApplicationAndUsePartial", null, new ViewDataDictionary())
</div>
在ajax方法的success
处理程序中,使用来自ajax调用的响应更新此div的innerHTML。 同样,在进行ajax调用时,您无需传递指定dataType值。
var myUrl= "http://" + window.location.host + "/UseAndNeed/ApplicationAndUse";
$.ajax({ type: "POST",
url : myUrl,
data: { idUniverse: selectedUniverse },
success:function(result){
$("myPartial").html(result);
}
});
始终应该使用Url.Action
或Url.RouteUrl
html帮助器方法来构建操作方法的URL。 无论您当前的页面/路径如何,它都会正确构建URL。
var myUrl= "@Url.Action("ApplicationAndUse","UseAndNeeed")";
如果您的js代码在razor视图中,则此方法有效。 但是,如果您的代码位于单独的javascript文件中,则可以使用上述帮助方法在razor视图中构建url,并将其保存在外部js文件代码可以访问的变量中。 一定要确保使用javascript命名空间,以避免全局javascript变量可能出现的问题。
@section Scripts
{
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.baseUrl = '@Url.Content("~")';
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>
}
在您的PageSpecificExternalJsFile.js
文件中,您可以像这样阅读它。
var myUrl= myApp.Urls.baseUrl+"UseAndNeed/ApplicationAndUse";
$("#myPartial").load(myUrl+'?idUniverse=someValue');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.