簡體   English   中英

帶有ajax的javascript函數的ASP.NET MVC調用服務器

[英]ASP.NET MVC calling server from javascript function with ajax

我正在嘗試從部分視圖中的javascript函數中調用控制器中的以下action方法:

[HttpPost]
    public JsonResult RemoveNotifications(IList<Notification> notifications)
    {
        Context.Notifications.RemoveRange(notifications);
        return new JsonResult();
    }

這是應該從視圖調用服務器的函數:

function show(message) {
    message += "</ul>"
    document.getElementById('notifications').innerHTML = message;
    $.ajax({
        url: '@Url.Action("RemoveNotifications", "Notification")',
        type: 'POST',
        data: { 'notifications': "@Model.Notifications" },
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data) {
        }
    });
}

第一部分工作正常,但是$ .ajax部分沒有任何作用。 我還在視圖頂部添加了以下內容:

<script src="TandForum.dk/Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="TandForum.dk/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="TandForum.dk/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

當您將@Model.Notifications傳遞給data參數時,它會嘗試對其進行序列化,以便可以將其傳遞給控制器​​操作。 由於javascript不了解您的Notification類的構造方式,因此將無法正常工作。

如果您需要指定要刪除的通知,則最好將通知ID的集合傳遞給操作,例如,如果您的Notification類具有名為Id int類型的屬性,則您的方法將變為:

public JsonResult RemoveNotifications(IEnumerable<int> notificationIds)
{
    Context.Notifications.RemoveAll(n => notificationIds.Contains(n.Id));
    return new JsonResult();
}

但是,如果您始終要刪除所有通知,請使用與最初填充視圖相同的集合,如上面的注釋所述。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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