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

二次信任 提交于 2019-12-10 15:48:00

问题


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 ?

回答1:


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!



来源:https://stackoverflow.com/questions/15931641/how-to-pass-data-from-view-to-controller-using-ajax-get-or-post-in-mvc-with-para

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!