Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you pass objects with MVC and jQuery AJAX?

I am finally experimenting and trying to learn MVC after years of asp.net.
I am used to using asp.net AJAX PageMethods where you can pass an object that automagically gets parsed to whatever type the parameter is in that method.

Javascript:

PageMethods.AddPerson({First:"John",Last:"Doe"});

Code-Behind:

[WebMethod]
public static Result AddPerson(Person objPerson)
{
    return Person.Save();
}

How would do this using MVC and jQuery?
Did just have to send strings and parse the json to object?

like image 840
Kenneth J Avatar asked Apr 27 '10 17:04

Kenneth J


People also ask

Can we implement AJAX using jQuery in MVC?

Using AJAX In ASP.NET MVC. Implementation of Ajax can be done in two way in ASP.Net Application: using Update Panel and, using jQuery.

How send AJAX file in MVC?

Uploading Files in MVC using jQuery AJAX FormDataGo to File->New->Project. Give a suitable name to the Application. Click OK. As you can see in the above image, two files are sent to C# ActionMethod, and both will be uploaded now.


1 Answers

That depends on how complex your form data is going to be. Let's use a jQuery example:

$.ajax({
    url: '\Persons\AddPerson', // PersonsController, AddPerson Action
    data: { First: "John", Last: "Doe" },
    type: 'POST',
    success: function(data, status)
    {
        alert('Method called successfully!');
    }
});

So we post two pieces of data. If the Person class has two properties called 'First' and 'Last', then the default ASP.NET MVC Model Binder should have no problems putting this form data into those properties (everything else will be defaulted).

Of course, you could always make a custom model binder for the Person type, and then you can take whatever form values you want and put them into any property at all, or call some other kind of logic.

like image 181
Tejs Avatar answered Sep 21 '22 19:09

Tejs