Search code examples
jqueryajaxasp.net-corerazorrazor-pages

Serialize form and attach a list of strings to it


I'm trying to serialise my form, but for some reason I can't make it work. The serialisation of the form is working. But the issue is, that I'll need to add a list afterwards, since it's not a part of the form, and when doing this my model is NULL when it's hitting my controllers endpoint.

        var valdata = $("#CreateForm").serialize();  

        var elements = document.querySelectorAll('#productCheckbox:checked');
        var checkedElements = Array.prototype.map.call(elements, function (el, i) {
            return el.name;
        });

        if (checkedElements.length == 0) {
            alert('You must select at least one product');
            return
        }

        var data = {
            model: valdata,
            products: checkedElements
        };

        $.ajax({
            url: '/Product/Create',
            type: 'post',
            dataType: 'json',
            data: data,
            success: function (data) {
                console.log('Success: ' + JSON.stringify(data))
            },
            error: function (data) {
                console.log('Error: ' + JSON.stringify(data))
            }
        });

The function of the Controller I'm hitting:

public ActionResult Create(Model model, object products)

The object products is working fine, but the model is null.

Do anyone have any suggestions, how to fix this? :-)

Please don't mind the name of the objects like Model, this is named something else in our project.


Solution

  • Here is a demo:

    Model:

    public class Model 
        {
            public int Id { get; set; }
            public string Name { get; set; }
    
        }
    

    View:

    <form id="CreateForm">
        <input name="Id" />
        <input name="Name" />
        <input type="button" value="submit" onclick="postdata()" />
    </form>
    <input type="checkbox" id="productCheckbox" name="vehicle1" value="Bike">
    <label for="vehicle1"> I have a bike</label>
    <br>
    <input type="checkbox" id="productCheckbox" name="vehicle2" value="Car">
    <label for="vehicle2"> I have a car</label>
    <br>
    <input type="checkbox" id="productCheckbox" name="vehicle3" value="Boat">
    <label for="vehicle3"> I have a boat</label>
    <br>
    

    js(I convert form data to a model):

    <script>
            function postdata(){
                var valdata = $("#CreateForm").serializeArray();
                var returnModel = {};
                for (var i = 0; i < valdata.length; i++) {
                    returnModel[valdata[i]['name']] = valdata[i]['value'];
                }
                
    
            var elements = document.querySelectorAll('#productCheckbox:checked');
            var checkedElements = Array.prototype.map.call(elements, function (el, i) {
            return el.name;
            });
    
            if (checkedElements.length == 0) {
            alert('You must select at least one product');
            return
            }
    
            var data = {
            model: returnModel,
            products: checkedElements
            };
    
            $.ajax({
            url: '/Test/Create',
            type: 'post',
            dataType: 'json',
            data: data,
            success: function (data) {
            console.log('Success: ' + JSON.stringify(data))
            },
            error: function (data) {
            console.log('Error: ' + JSON.stringify(data))
            }
            });
            }
        </script>
    

    result: enter image description here