Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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>
share|improve this question
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 – Stephen Muecke Apr 19 at 22:33

1 Answer 1

up vote 0 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.