簡體   English   中英

使用TempData完成時,MVC3 Ajax ActionLink可以調用javascript函數

[英]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" })

我以為可以通過從ActionLinkOnComplete選項中將調用添加到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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM