2

Disclaimer: I am a total noob when it comes to ASP.NET.

I am using the following jQuery code to submit my form:

            $.ajax({
                url: '/Foo/Save',
                type: 'POST',
                data: $('#dataInputForm').serialize(),
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    alert(data.success);
                },
                error: function () {
                    alert("error");
                }
            });

My Foo controller code is this:

    [HttpPost]
    public ActionResult Save()
    {
        return Json(new { success = true });
    }

I know the AJAX post is working because I am seeing the alert with "success". Next, I would like to see a var dump somehow of my serialized form. I honestly do not know where to begin on the controller end but I would like my success alert to just dump my serialize form data just so that I can confirm that the form data that was submitted.

Essentially, this is what I would like the success alert to look like:

a=1&b=2&c=3&d=4&e=5

BONUS: I would love to see an alternative way of submitting the data in JSON and seeing the success alert in JSON.

2
  • Have you considered using the jQuery Form plugin instead? Does a swell job of handling AJAXification of <form />s. Commented Sep 20, 2011 at 22:59
  • @kid0m4n No I have not. Thanks for the recommendation. At first glance, it is pretty sweet and helps streamline the client end of stuff. My main issue is with the server stuff. I'm a PHP guy struggling with ASP.NET =) Commented Sep 20, 2011 at 23:04

2 Answers 2

4

firstly, .serialize() does not produce json, so the specified contentType is wrong. you can drop the contentType option and $.ajax() will use the default 'application/x-www-form-urlencoded'.

next, on the controller, you need to bind the posted data to some object. if you don't have an object defined that models your form data, you can use a FormCollection to build your result:

[HttpPost]
public ActionResult Save(FormCollection collection)
{
    var result = new {Foo1 = collection["Foo1"], Foo2 = collection["Foo2"]};

    return Json(result);
}

in your success handler, you can then display the properties:

success: function(data) {
    alert(data.Foo1);
    alert(data.Foo2);
}

or convert the object to a json string using this utility like so:

success: function(data) {
    alert(JSON.stringify(data));
}

for further reference:

convert json object to string

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks ok. I have removed the contentType option and used the controller and the alert now says "undefined". I guess it is now expecting a JSON object instead of the serialized string?
what are you alerting? data.success will be undefined since we're sending back a different object now. did you try alert(data)?
yes, you're right. stupid mistake. I can now see a comma delimited list of of all my input names but no values. Is this what I should expect from this output? (I do values in my text boxes)
edited my answer to show you how to get values from the FormCollection, assuming your form has fields named Foo1 and Foo2
Ok...I have edited the field names to "Foo1" and "Foo2" and the alert that I see is [object Object].
|
0

You might have to change the method signature of the method so that it is of time Stream. Then you'll have to parse through the stream as a string and split the arguments by & (ampersands) where you'll have different KVPs.

public Stream samplePost(Stream stream)
    {
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
        StreamReader sr = new StreamReader(stream);
        string stringStream = sr.ReadToEnd();
        sr.Dispose();
        NameValueCollection kvp = HttpUtility.ParseQueryString(stringStream);
        var number1 = Convert.ToInt32(kvp["number1"]);
        var number2 = Convert.ToInt32(kvp["number2"]);
        var sum = number1 + number2;

        byte[] byteArray = Encoding.ASCII.GetBytes("SUM IS " + sum.ToString());
        MemoryStream s = new MemoryStream(byteArray);
        return s;
    }

That's a sample for taking in two numbers and returning them as a sum. I think this should set you on your way.

3 Comments

Wow...this is a lot more complex than I expected. In PHP, this is 1-liner =)
I'm getting errors left and right on this code. For example: The name 'WebOperationContext' does not exist in this current context. I did add the using System.IO though to allow use of Stream.
The example is for a WCF service, so it might not exist - try to remove that line and see what the default response type is for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.