简体   繁体   English

将 ajax 请求中的多个参数传递给 function 后面的 C# 代码

[英]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.我无法将多个参数从我的 ajax function 传递到我的 C# ZC1C425208E68384FC14A7A。 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.当我在 ajax function 中仅传递 1 个参数(vthaForm)时,它会正确发送到 OnPostApprove 方法,并填写 vthaForm 中的所有属性。 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.但是,当我尝试在 ajax function 的数据中包含评论参数时,到达 OnPostApprove 方法时的 vthaForm 和评论变量都没有使用正确的值初始化。

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.简短的故事是你不能像这样绑定多个参数,它必须是一个 object。

Read through this and see if it answers your question.通读这个,看看它是否回答了你的问题。

WebAPI Multiple Put/Post parameters WebAPI 多个 Put/Post 参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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