[英]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.