[英]MVC3 Ajax ActionLink to call javascript function when completed with TempData
我一直在嘗試獲取通知,以顯示用戶何時在控制器中調用動作。 這對於我的大多數操作都可以正常工作,但是我使用Ajax.ActionLink
刪除了我的項目,因此該頁面沒有刷新,並且沒有調用javascript函數,因此沒有顯示通知。
在_Layout
頁面上,我具有如下所示的通知系統:
<script type="text/javascript">
//Used to display and close the system notifications
$(document).ready(function notify() {
$("#NotificationBox").show("slide", { direction: "down" }, 1000);
if ($("#NotificationAutoHide").val() == "true") {
$("#NotificationBox").delay(5000).hide("slide", { direction: "down" }, 1000);
}
});
</script>
<div id="NotificationDiv">
@if (TempData["Notification"] != null)
{
@Html.Hidden("NotificationAutoHide", TempData["NotificationAutoHide"])
<div id="NotificationBox" class="@TempData["NotificationCSS"]" style="display: none">
@TempData["Notification"]
</div>
}
</div>
在我的Index
視圖(使用布局頁面)中,我有Ajax ActionLink
,它在控制器中調用了Delete
操作,該操作還填充了必需的TempData
屬性。
@Ajax.ActionLink("Delete", "Delete", "MyController",
new { id = item.UserID },
new AjaxOptions {
HttpMethod = "Delete",
OnBegin = "JSONDeleteFile_OnBegin",
OnComplete = "notify"
},
new { @class = "delete-link" })
我以為可以通過從ActionLink
的OnComplete
選項中將調用添加到notify
函數中,然后一切正常,但是不幸的是,這似乎不起作用。
我見過一些例子,表明發送TempData
通過回JsonResult
從我conntroller,但我不知道如何打那個到我現有的代碼。 (我的控制器已經返回了JsonResult對象用於其他用途)
誰能幫助我從Ajax調用中獲取TempData
並執行我的通知系統?
非常感謝你花時間陪伴。
由於TempData是服務器端代碼,因此我認為不可能。 您應該通過JsonResult返回此信息。
例:
public JsonResult Delete(int id) { //do stuff return Json(new {param1 = "what you need", param2 = "more info"}, JsonRequestBehavior.AllowGet); }
確保您的notify
函數是公開可見的,以便您可以從AJAX成功回調中調用它:
<script type="text/javascript">
function notify() {
$("#NotificationBox").show("slide", { direction: "down" }, 1000);
if ($("#NotificationAutoHide").val() == "true") {
$("#NotificationBox").delay(5000).hide("slide", { direction: "down" }, 1000);
}
}
$(document).ready(notify);
</script>
聲明notify
函數的方式使得不可能從外部范圍調用此函數:
$(document).ready(function notify() { ... });
我什至不知道這是否是有效的JavaScript語法。 從未見過有人使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.