how to pass data from View to Controller using ajax get or post in mvc with parameters

user2232861 picture user2232861 · Apr 10, 2013 · Viewed 23.5k times · Source

I am trying to pass data from View to Controller Action Method using ajax as follows:-

I have Membership instance of user which I passed in from another controller to this view below using viewbag somewhat like this ViewBag.MyUser = MyUser;

Now I want to pass 'MyUser' to another Controller form this view using ajax as below.

 $('#Link').click(function () {      
        $.ajax({
            url: http://localhost/Account/Process,
            type: 'POST',
            data: '@ViewBag.MyUser',
            success: function () {
            },
            error: function () {                
            }
        });

The ActionMethod to which I am posting is as follows

public ActionResult Process(MembershipUser MyUser)
{
   //Do somethihng with MyUser
}

If I pass do ajax post, I get error internally at BeginExecuteCore(AsyncCallback callback, object state) stating that 'No parameterless constructor defined for this object.' and control does not even comes to my actionmethod.

If I remove the parameter (MembershipUser MyUser) from Action Method it posts to Action method, but then

  1. how can i pass 'MyUser' in such case without parameter from that view to controller ?
  2. is there something wrong with routes ? if yes what should be the route ?
  3. or should i use get or post ?
  4. Where should i cast the MyUser back to MembershipUser ?

Answer

danieleduardo29 picture danieleduardo29 · Apr 10, 2013

The problem is you can't pass MyUser as parameter from JQuery because JQuery doesn't know the class MembershipUser. Remember that JQuery is a client side language and MembershipUser is defined in C# on the server side.

You could pass the properties that you need from the MyUser object to the Process action using GET as follows (supossing that the MyUser object has and ID an a Name):

$('#Link').click(function () {      
    $.ajax({
        url: http://localhost/Account/Process,
        type: 'GET',
        data: { 
                id: "@ViewBag.MyUser.ID",
                name: "@ViewBag.MyUser.Name" 
              },
        success: function () {
        },
        error: function () {                
        }
    });

The action should be something like this:

public ActionResult Process(int id, string name)
{
   //Do something
}

I hope it helps you!