[英]Calling an action method asynchronously doesn't load the view
我在一個視圖中有2-3個局部視圖。 其中每個都有Web服務調用。 這些是如下的同步調用。 我想異步加載“地址”局部視圖。 我正在嘗試使用ajax加載它。在文檔ready()中
我可以像通過ajax加載視圖一樣,從個人視圖行中刪除對地址/索引的操作調用嗎? 如果我不刪除它,那么它會錯誤地指出未通過模型,如果我刪除了它,則不會加載部分視圖。 我究竟做錯了什么?
另外,“個人”視圖和“地址”視圖位於不同的文件夾中。 這是什么導致它無法加載?
個人觀點:
<div id="PersonalInfo">
Html.Action("_Index", PersonalInfo)
</div>
<div id="Address">
Html.Action("../Address/_Index", Address) // Can i remove this line as i would be loading the
view via ajax?
</div>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'GET',
url: '@Url.Action("Index", "Address")',
dataType: 'json',
success: function (result) {
$('#Address').html(result); // where #Address is the div id in Address Partial View
}
});
});
</script>
地址視圖
<div id="Address">
// address displayed in a grid
</div>
地址控制器
[HttpGet]
public ActionResult Index()
{
//call service and get List<Address>()
var address= getAddress();
return this.PartialView("_Index", address);
}
您在這里遇到一些問題:
Action
擴展方法 這個...
<div id="PersonalInfo">
Html.Action("_Index", PersonalInfo)
</div>
應該使用@
轉義字符來指示剃刀停止處理html並開始處理剃刀語法。 這是您應該如何使用它的方法...
<div id="PersonalInfo">
@Html.Action("_Index", PersonalInfo)
</div>
確保_Index
操作方法存在於您在此處調用的任何控制器中
Action
擴展方法 這個...
<div id="Address">
Html.Action("../Address/_Index", Address)
</div>
肯定會引發各種異常,因為此重載的第一個參數必須是您嘗試調用的Action方法的名稱。 如果此操作方法在不同的控制器中(與當前上下文不同),則應使用不同的重載,該重載可以如下指定控制器名稱...
<div id="Address">
Html.Action("Index", "Address", null)
</div>
您應該在這里注意到兩件事:
null
如@dotnetstep所述,此jQuery ajax方法...
$.ajax({
type: 'GET',
url: '@Url.Action("Index", "Address")',
dataType: 'json',
success: function (result) {
$('#Address').html(result);
}
});
應該將dataType
選項設置為html
因為您要調用的操作方法方法以html格式而不是json響應數據。 更好的是,您根本不需要指定任何內容,jQuery會做出明智的猜測……
$.ajax({
type: 'GET',
url: '@Url.Action("Index", "Address")',
success: function (result) {
$('#Address').html(result);
}
});
數據類型應為HTML。
<div id="PersonalInfo">
Html.Action("_Index", PersonalInfo)
</div>
<div id="Address">
Html.Action("../Address/_Index", Address) // Can i remove this line as i would be loading the
view via ajax?
</div>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'GET',
url: '@Url.Action("Index", "Address")',
dataType: 'HTML',
success: function (result) {
$('#Address').html(result); // where #Address is the div id in Address Partial View
}
});
});
</script>
Address View
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.