How to pass objects using MVC and jQuery AJAX?

I am finally experimenting and trying to learn MVC after many years of asp.net.
I use asp.net AJAX PageMethods, where you can pass an object that is automatically parsed for any type of parameter in this method.

JavaScript:

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

Code-Behind:

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

How to do this using MVC and jQuery?
Need to just send strings and parse json for an object?

+5
source share
5 answers

It depends on how complex your form data is. Let jQuery example be used:

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

, . Person , "First" "Last", ASP.NET MVC Model Binder ( ).

, Person, , , - , .

+4

, AJAX ASP.NET MVC. :

  • HTTP GET, POST
  • jQuery $.get, $.getJSON, $.post
  • ( JSON)
  • MVC AJAX

AJAX ASP.NET MVC jQuery

+2

ajax , ModelBinder - . .

public ActionResult MyAction(MyObject obj)
{
}

MyObject , .

public ActionResult MyAction(FormCollection stuff)
{
   MyObject obj = new MyObject();
   TryUpdateModel(obj);
}

. ModelBinder .

ModelState, , - , .

. .

For advanced binding to lists and dictionaries, see Phil Haack's post .

0
source

You can do something like this:

 var person = {};
 person["First"] = $("#FirstName").val();
 person["Last"] = $("#LastName").val();

 $.ajax({
      type: "POST",
      contentType: "application/json; charset=utf-8",
      url: "/Admin/AddPerson",
      data: JSON.stringify(person),
      dataType: "json",
      success: function(result) {

      },
      error: function(result) {

      }
 });

and then on the admin controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddRelease(Person p)
{
    // Code to add person            

}

The JSON.stringify method is available from here . You can also use the model, rather than the Person object, as a parameter so that you can handle all your validation.

0
source

I think I'm a scammer and do the following:

        $("#ProgressDialog").dialog({
            autoOpen: false,
            draggable: false,
            modal: true,
            resizable: false,
            title: "Loading",
            closeOnEscape: false//,

            //  open: function () { $(".ui-dialog-titlebar-close").hide(); } // Hide close button
        });
       $("form").live("submit", function (event) {
                event.preventDefault();
                var form = $(this);
                $("#ProgressDialog").dialog("open");
                $.ajax({
                    url: form.attr('action'),
                    type: "POST",
                    data: form.serialize(),//USE THIS to autoserialize!
                    success: function (data) {
                        $("#dialog").dialog({height:0});
                    },
                    error: function (jqXhr, textStatus, errorThrown) {
                        alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
                    },
                    complete: function () {
                        $("#ProgressDialog").dialog("close");

                    }
                });
            });
        });

<div id="ProgressDialog" style="text-align: center; padding: 50px;">
    <img src="@Url.Content("~/Content/ajax-loader.gif")" width="128" height="15" alt="Loading" />
</div>
0
source

All Articles