Serializing MVC form to JSON in JQuery

I want to Serialize my MVC form to JSON using JQuery and then I want to Deserialize some values ​​like the value of an input field in the backend in C #, but I cannot serialize it to json ... Please help me with this issue. this is my code.

<script type="text/javascript">
    $(function () {

        $('#btnsearch').click(function (e) {

            var searchname = $('#txtsearch').val();

            var form = $(this).serializeArray();

            DrawTable(form);
        });



        function DrawTable() {
            var props = [];
            props.push({ name: "FirstName", value: firstname });
            BindDataTable({ AllowPaging: true, ShowFilter: false, ShowEditLink: true, EmptyTableText: 'No Data Found', SortIndex: 0, SortDirection: "asc" },
                              "#tblCustomers",
                              "@Url.Action("GetAllCustomers", "Customer")",
                              props,
                              [{ name: "Id", cellClass: "alignCenter", Sortable: true, index: 0 }, { name: "FirstName" }, { name: "ABN" }, { name: "Phone" }, { name: "Email" }, { name: "Address1" }, { name: "City" }, { name: "Country" }],
                              [{ name: "Id", type: "anchor", title: 'customerTable', viewtitle: 'View', link: '@Url.Action("Edit", "Customer")', index: 0 }]);

        } 

       // DrawTable(data);
        //$('#myInputTextField').on('keyup', function () {
        //    oTable.search($(this).val()).draw();
        //});



    });

        </script>

      

+3


source to share


2 answers


You cannot use $(this).serializeArray();

because it this

refers to $('#btnsearch')

, which is not a form.



Use $("#your_form_id).serializeArray();

or $("#your_form_id).serialize()

.

0


source


Yes, this is a very old question and there are many similar questions with answers:

But this assignment is specifically for Asp.MVC: I checked most of the answers and was unable to serialize forms encoded the way Asp.mvc works when there is a list type property that Asp.MVC encodes as

   TheProperty[1].SubProperty=Value
   TheProperty[2].SubProperty=Value

      



The only serializer that correctly addresses this case is this , when configured with the option

{ associativeArrays: false }

      

(thanks to raphaelm22 for your solution!)

0


source







All Articles