0

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>
1
  • 2
    @Model.Notifications will return a string (something like "System.Collections.Generic.IList<Notification>", not the collection. What is the point of this. You sent the collection to the view from the controller so you already know what it is. There is no reason to send it from the view to the controller, just get the same collection again in the RemoveNotifications() method Commented Apr 19, 2015 at 22:33

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.