Search code examples
c#asp.netajaxasp.net-mvc-4

Pass Model as a list from View to Controller using ajax call


I have trouble trying to send my entire model which actually is a List<Account> using ajax call.

Providing the following code:

@model List<ValidationAccount>

<input type="button" id="SubmitAccounts" value="Final Proceed">

$("#SubmitAccounts").click(function () {
            $.ajax({
                url: '/setupAccounts/ActivateAccounts',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                cache: false,
                dataType: 'json',
                data: JSON.stringify(Model),
                success: function (data) {
                    $(body).html(data);
                }, error: function (data) {
                }
            });
        });

I've tried using simple Model and @Model but doesn't work. What can I do in this situation? (So I want to pass as data my model (my List)).


Update

Method Signature:

[HttpPost]
public string ActivateAccounts(List<ValidationAccount> Accounts)
{
    return "Success";
}

Update 2

My model:

public class ValidationAccount
    {
        public string Faculty { get; set; }
        public string Programme { get; set; }
        public string Year { get; set; }
        public string Email { get; set; }
    }

Thanks.


Solution

  • Using @Model is going to return the name of the collection such as "System.Collections.Generic.List[YourAssembly.ValidationAccount]" not the objects in the collection. You could possibly serialize the collection to ViewBag then post it back (not tested) but it seems an unnecessary performance hit to send the data both ways.

    Instead you could store the filtered results from you Proceed method in session and retrieve it in the ActivateAccounts method to avoid posting anything back.