简体   繁体   中英

Passing multiple parameters in ajax request to C# code behind function

I am having trouble passing multiple parameters from my ajax function, to my C# function. When I pass just 1 parameter(vthaForm) in my ajax function, it gets sent to the OnPostApprove method properly, with all the properties in vthaForm filled out. But when I try and include the comment parameter in the data from the ajax function, both vthaForm and comment variables on arrival to the OnPostApprove method are not initialized with the proper values.

I've tried a couple different solutions from other posts, but have not had any luck.

If anyone can point me in the right direction, it would be greatly appreciated.

//This is my C# code on the codebehind page Approver.cshtml.cs
public IActionResult OnPostApprove([FromBody]VthaForms vthaForm, [FromBody]string comment){;}


//This function is my Approver.cshtml razor page
//vthaform = JSON object, handler ="Approve", _comment is a string

function approveform(vthaform, handler, _comment) { 
        var package = {
            vthaForm: vthaform, 
            comment: _comment
        };

        $.ajax({
            type: "POST",
            url: 'Approver/?handler=' + handler,
            data: JSON.stringify(package),
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (data) {
            console.log(data.name);
            alert("Succesfully approved " + data.name +"'s VTHA with id: " + data.id + "." )
        });
    }

Short story is you can't bind to multiple parameters like that, it has to be one object.

Read through this and see if it answers your question.

WebAPI Multiple Put/Post parameters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM