Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?
like image 879
user2232861 Avatar asked Jan 14 '23 17:01

user2232861


1 Answers

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!

like image 184
danieleduardo29 Avatar answered Jan 19 '23 11:01

danieleduardo29