简体   繁体   中英

ASP.NET MVC calling server from javascript function with ajax

I am trying to call the following action method in a controller from a javascript function in a partial view:

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

This is the function that should call the server from the view:

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) {
        }
    });
}

The first part works fine, but the $.ajax part dosen't do anything. I also have the following added at the top of my view:

<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>

When you pass @Model.Notifications into the data parameter it is attempting to serialize it so that it can be passed to the controller action. Because javascript has no knowledge of how your Notification class is constructed, this will not work.

If you need to specify which Notifications are to be removed, it would be better to pass to the action a collection of Notification IDs, so for example if your Notification class has a property of type int called Id then your method becomes:

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

But if you always want to remove all Notifications, just use the same collection that you used to populate the view in the first place, as the comment above mentions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM