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.

Allen Liu
  • 3,948
  • 8
  • 35
  • 47
  • Have you considered using the jQuery Form plugin instead? Does a swell job of handling AJAXification of
    s.
    – kidoman Sep 20 '11 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 =) – Allen Liu Sep 20 '11 at 23:04

2 Answers2

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

Community
  • 1
  • 1
Omer Bokhari
  • 57,458
  • 12
  • 44
  • 58
  • 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? – Allen Liu Sep 20 '11 at 23:36
  • what are you alerting? data.success will be undefined since we're sending back a different object now. did you try alert(data)? – Omer Bokhari Sep 20 '11 at 23:41
  • 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) – Allen Liu Sep 20 '11 at 23:51
  • edited my answer to show you how to get values from the FormCollection, assuming your form has fields named Foo1 and Foo2 – Omer Bokhari Sep 21 '11 at 00:04
  • Ok...I have edited the field names to "Foo1" and "Foo2" and the alert that I see is `[object Object]`. – Allen Liu Sep 21 '11 at 00:39
  • right, because you now have a javascript object. see my edit for reading the object properties or converting the object to json – Omer Bokhari Sep 21 '11 at 01:31
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.

konp
  • 1
  • Wow...this is a lot more complex than I expected. In PHP, this is 1-liner =) – Allen Liu Sep 20 '11 at 23:21
  • 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`. – Allen Liu Sep 20 '11 at 23:26
  • 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. – konp Sep 21 '11 at 00:02