tags:

views:

852

answers:

3

I was wondering if it is possible to pass the forms collection from within an ajax method in jQuery?

$.ajax({
        type: "POST",
        url: "/page/Extension/" + $("#Id").val(),
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            $("#result").html(msg);
            false;
        }
    });

If it is possible to pass in the forms collection then when it arrives at the method within c# how to you read it in?

+1  A: 

You can use the Ajax.BeginForm method from ASP.NET MVC. It will use Microsoft's ajax to do the request, but you can have a JQuery method execute upon completion. Or you can use an UpdatePanel and register a javascript to run with the ScriptManager once the UpdatePanel loads. Another thing you could try is using a jquery like the following: $(':input') to get a collection of all input, textarea, select and button elements(JQuery documentation), and pass that as the data into your request.

Yuriy Faktorovich
A: 

You can do something like this:

var form = $("#myForm").serialize();
 $.post("/Home/MyUrl", form, function(returnHtml) 
        {
            //callback
        });

Then on the C# side you should be able to do something like this:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult MyUrl(FormCollection collection)
    {
        //do what you gotta do
    }

I think this should work.

EDIT: I just noticed that I simply assumed you were referring to ASP.NET MVC. If not, let me know as this answer is specific to MVC.

BFree
A: 

Got this working all okay, and it returns the input form collection in the FormCollection

input = $(':input')
$.ajax({
    type: "POST",
    url: "/page/Extension/" + $("#Id").val(),
    data: input,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        $("#result").html(msg);
        false;
    }
});
Coppermill