繁体   English   中英

ASP.NET 核心 MVC Ajax 调用未将参数传递给 api Z594C103F2C6E04C3D18AB059F031E 方法

[英]ASP.NET Core MVC Ajax call not passing parameters to api controller method

我正在尝试使用 ajax 调用 API controller 方法并传递一些参数。 正在调用 api 方法,但值在 controller 方法中以 null 的形式出现。

Using same ajax call, another controller (not api controller) having same method receives parameter values and returns results but i'm stuck with passing values to api controller method. 请帮助

 $(document).ready(function ()
                {
                    $("#DropDownName").change(function ()
                    {
                        $.ajax({
                            type: "POST",
                            dataType: "text",
                            url: "@(Url.Action("SampleAction", "XYZController"))",
                            data: {
                                "param1": $("#DropDownName :selected").val(),
                                "param2": $("#input2").val(),
                                "param3": $("#input3").val()
                            },

                            success: function (response) {

                            document.getElementById("result").textContent = "Result: " + response;
                        },


                        });
                    }); 
                });

API Controller 方法

    [Route("api/[controller]")]
    [ApiController]
    public class XYZController : ControllerBase
    {
        [ActionName("SampleAction")]
        [HttpPost]
        public decimal SampleAction(string dropdownselectedvalue,decimal input2, int input3)
        {
         //code here - This method is getting called but getting null parameter values
        }
    }

如下更改您的 ajax:

data: {
        "dropdownselectedvalue":$("#DropDownName :selected").val(),
        "input2": $("#input2").val(),
        "input3": $("#input3").val(),
},

确保在后端代码中添加FromForm

[Route("api/[controller]")]
[ApiController]
public class XYZController : ControllerBase
{
    [ActionName("SampleAction")]
    [HttpPost]
    public decimal SampleAction([FromForm]string dropdownselectedvalue,
        [FromForm] decimal input2, [FromForm] int input3)
    {
        return input2;
        //code here - This method is getting called but getting null parameter values
    }
}

暂无
暂无

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

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