控制器动作中的AJAX空参数 [英] AJAX null parameter in controller action

查看:48
本文介绍了控制器动作中的AJAX空参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将值从我的视图传递给控制器​​操作,但是每次我执行此参数时,该参数都为null.我看过许多关于相同内容的文章,但似乎不太正确..我的代码在下面

I want pass values from my view to a controller action however every time i do the parameter is null. I've seen multiple posts about the same things but can't quite seem to get it right.. my code is below

控制器动作

[HttpPost]
    public IActionResult GetTest(string data)
    {
        var jSon = JsonConvert.SerializeObject(channles[0]);

        return Json(jSon);
    }

查看(AJAX)代码

function testAjax() {

        $("#searchButton1").click(function () {
            $.ajax({
                type: "POST",
                url: '@Url.Action("GetTest", "DataGridWebApi")',
                data: { data: "test" },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
}

我在控制器操作中遇到了断点,但参数始终为null.我还尝试将控制器动作更改为接受对象而不是字符串,但似乎没有任何作用.

I hit the breakpoint in my controller action but the parameter is always null. I've also tried changing my controller action to accept an object instead of a string but nothing seems to work.

我在做什么错?

推荐答案

您需要进行两项更改.您确实需要在参数上使用 [FromBody] :

You need to make two changes. You do need [FromBody] on the param:

public IActionResult GetTest([FromBody]string data)

然后,您只需要将字符串作为JSON发送:

Then, you need to send just the string, as JSON:

data: JSON.stringify("test")

这似乎有些怪异,但是如果没有 JSON.stringify ,它将作为 test 发送,并且您需要"test" .简而言之,您要发送的字符串具有JSON内容类型,因此它必须是 JSON字符串.

That may seem a little weird, but without JSON.stringify it will be sent as just test, and you need "test". In short, you're sending a string with a JSON content type, so it must be a JSON string.

这篇关于控制器动作中的AJAX空参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆