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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With