Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Zac 239 posts 541 karma points
    Apr 06, 2012 @ 01:21
    Zac
    0

    Invalid JSON primitive when posting form via jquery

    I'm trying to post form data to my custom controller via jquery and keep receiving the  "Invalid JSON primitive: Number.ValueAsDecimal" (or any other input field name) .  The form works fine when posted synchronously.

     

    The post is pretty simple, I just want to post my form (which is dynamic) to my Controller.  Here's what I currently have:

     

    jQuery: 

                $.post($("#myForm").attr('action'), $("#myForm").serialize(), function (retData) {
                    alert(retData);
                });

    Controller Declaration:

            [HttpPost]
            public string SaveDataAjax(FormCollection data)
            {
    ...
    }

    Any ideas?  

     

     

     

  • Zac 239 posts 541 karma points
    Apr 10, 2012 @ 01:46
    Zac
    0

    For others running into the same problem, you can't send a jQuery serialized form like this in Umbraco 5 as it will crash before routing to the correct page.

    Umbraco expects "json" data to be sent in as a List of string pairs (List<string[]>)

    I fixed this by doing the following:

    jquery:

    replaced $("#myForm").serialize with a call to this function:

     

        // pass in the formId. I.E. "#form"
        // returns the umbraco "json" string
        function getUmbFormData(formId) {
            var umbData = "[ ";
            $.each($(formId + " input, " + formId + " select, " + formId +" textarea"), function(i,element) {
                if(i>0)
                    umbData+=",";

                umbData += "['"+$(element).attr("id") + "','"+ $(element).val()+"']";
            });
            umbData += " ]";
            return umbData;
        }

    and replaced the controller with:

           [HttpPost]
            public string SaveDataAjax(List<string[]> data)
            {
    ...
    }

    Hope this helps others!

     

Please Sign in or register to post replies

Write your reply to:

Draft