使用 jQuery $.ajax() 和 $.post() 将字符串数据发送到 MVC 控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1843017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:14:51  来源:igfitidea点击:

Sending String Data to MVC Controller using jQuery $.ajax() and $.post()

asp.net-mvcjquerycontroller

提问by MegaMatt

There's got to be something I'm missing. I've tried using $.ajax() and $.post() to send a string to my ASP.NET MVC Controller, and while the Controller is being reached, the string is null when it gets there. So here is the post method I tried:

一定有我遗漏的东西。我尝试使用 $.ajax() 和 $.post() 将字符串发送到我的 ASP.NET MVC 控制器,当到达控制器时,该字符串在到达那里时为空。所以这是我尝试的post方法:

$.post("/Journal/SaveEntry", JSONstring);

And here is the ajax method I tried:

这是我尝试过的ajax方法:

$.ajax({
    url: "/Journal/SaveEntry",
    type: "POST",
    data: JSONstring
});

Here is my Controller:

这是我的控制器:

public void SaveEntry(string data)
{
    string somethingElse = data;
}

For background, I serialized a JSON object using JSON.stringify(), and this has been successful. I'm trying to send it to my Controller to Deserialize() it. But as I said, the string is arriving as null each time. Any ideas?

作为背景,我使用 JSON.stringify() 序列化了一个 JSON 对象,这已经成功了。我正在尝试将它发送到我的控制器以反序列化()它。但正如我所说,字符串每次都以空值到达。有任何想法吗?

Thanks very much.

非常感谢。

UPDATE:It was answered that my problem was that I was not using a key/value pair as a parameter to $.post(). So I tried this, but the string still arrived at the Controller as null:

更新:有人回答说我的问题是我没有使用键/值对作为 $.post() 的参数。所以我尝试了这个,但字符串仍然作为空值到达控制器:

$.post("/Journal/SaveEntry", { "jsonData": JSONstring });

回答by MegaMatt

Answered. I did not have the variable names set correctly after my first Update. I changed the variable name in the Controller to jsonData, so my new Controller header looks like:

回答。第一次更新后,我没有正确设置变量名称。我将 Controller 中的变量名称更改为 jsonData,因此我的新 Controller 标头如下所示:

public void SaveEntry(string jsonData)

and my post action in JS looks like:

我在 JS 中的 post 操作如下所示:

$.post("/Journal/SaveEntry", { jsonData: JSONstring });

JSONstring is a "stringified" (or "serialized") JSON object that I serialized by using the JSON pluginoffered at json.org. So:

JSONstring 是一个“字符串化”(或“序列化”)JSON 对象,我使用json.org 提供的JSON 插件对其进行序列化。所以:

JSONstring = JSON.stringify(journalEntry);  // journalEntry is my JSON object

So the variable names in the $.post, and in the Controller method need to be the same name, or nothing will work. Good to know. Thanks for the answers.

所以 $.post 中的变量名和 Controller 方法中的变量名需要是相同的名称,否则什么都不起作用。很高兴知道。感谢您的回答。

回答by prodigitalson

Final Answer:

最终答案:

It seems that the variable names were not lining up in his post as i suggested in a comment after sorting out the data formatting issues (assuming that was also an issue.

在整理了数据格式问题(假设这也是一个问题)后,我在评论中建议的那样,变量名称似乎没有在他的帖子中排列。

Actually, make sure youre using the right key name that your serverside code is looking for as well as per Olek's example - ie. if youre code is looking for the variable data then you need to use data as your key. – prodigitalson 6 hours ago

@prodigitalson, that worked. The variable names weren't lining up. Will you post a second answer so I can accept it? Thanks. – Mega Matt 6 hours ago

实际上,请确保您使用的是服务器端代码正在寻找的正确密钥名称以及根据 Olek 的示例 - 即。如果您的代码正在寻找可变数据,那么您需要使用数据作为键。– prodigitalson 6 小时前

@prodigitalson,有效。变量名称没有对齐。您会发布第二个答案以便我接受吗?谢谢。– Mega Matt 6 小时前

So he needed to use a key/value pair, and make sure he was grabbing the right variable from the request on the server side.

所以他需要使用一个键/值对,并确保他从服务器端的请求中获取了正确的变量。



the data argument has to be key value pair

数据参数必须是键值对

$.post("/Journal/SaveEntry", {"JSONString": JSONstring});

回答by prodigitalson

It seems dataType is missed. You may also set contentType just in case. Would you try this version?

似乎缺少 dataType。您也可以设置 contentType 以防万一。你会试试这个版本吗?

$.ajax({
    url: '/Journal/SaveEntry',
    type: 'POST',
    data: JSONstring,
    dataType: 'json',
    contentType: 'application/json; charset=utf-8'
});

Cheers.

干杯。

回答by ngwanevic

Thanks for answer this solve my nightmare.

感谢您的回答,这解决了我的噩梦。

My grid

我的格子

..
.Selectable()
.ClientEvents(events => events.OnRowSelected("onRowSelected"))
.Render();

<script type="text/javascript">
function onRowSelected(e) {
        id = e.row.cells[0].innerHTML;
        $.post("/<b>MyController</b>/GridSelectionCommand", { "id": id});
    }
</script>

my controller

我的控制器

public ActionResult GridSelectionCommand(string id)
{
     //Here i do what ever i need to do
}

回答by Md. Nazrul Islam

The Way is here.

道就在这里。

If you want specify

如果你想指定

dataType: 'json'

数据类型:'json'

Then use,

然后使用,

$('#ddlIssueType').change(function () {


            var dataResponse = { itemTypeId: $('#ddlItemType').val(), transactionType: this.value };

            $.ajax({
                type: 'POST',
                url: '@Url.Action("StoreLocationList", "../InventoryDailyTransaction")',
                data: { 'itemTypeId': $('#ddlItemType').val(), 'transactionType': this.value },
                dataType: 'json',
                cache: false,
                success: function (data) {
                    $('#ddlStoreLocation').get(0).options.length = 0;
                    $('#ddlStoreLocation').get(0).options[0] = new Option('--Select--', '');

                    $.map(data, function (item) {
                        $('#ddlStoreLocation').get(0).options[$('#ddlStoreLocation').get(0).options.length] = new Option(item.Display, item.Value);
                    });
                },
                error: function () {
                    alert("Connection Failed. Please Try Again");
                }
            });

If you do not specify

如果不指定

dataType: 'json'

数据类型:'json'

Then use

然后使用

$('#ddlItemType').change(function () {

        $.ajax({
            type: 'POST',
            url: '@Url.Action("IssueTypeList", "SalesDept")',
            data: { itemTypeId: this.value },
            cache: false,
            success: function (data) {
                $('#ddlIssueType').get(0).options.length = 0;
                $('#ddlIssueType').get(0).options[0] = new Option('--Select--', '');

                $.map(data, function (item) {
                    $('#ddlIssueType').get(0).options[$('#ddlIssueType').get(0).options.length] = new Option(item.Display, item.Value);
                });
            },
            error: function () {
                alert("Connection Failed. Please Try Again");
            }
        });

If you want specify

如果你想指定

dataType: 'json' and contentType: 'application/json; charset=utf-8'

数据类型:'json' 和内容类型:'应用程序/json;字符集=utf-8'

Then Use

然后使用

$.ajax({
            type: 'POST',
            url: '@Url.Action("LoadAvailableSerialForItem", "../InventoryDailyTransaction")',
            data: "{'itemCode':'" + itemCode + "','storeLocation':'" + storeLocation + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            cache: false,
            success: function (data) {

                $('#ddlAvailAbleItemSerials').get(0).options.length = 0;
                $('#ddlAvailAbleItemSerials').get(0).options[0] = new Option('--Select--', '');

                $.map(data, function (item) {
                    $('#ddlAvailAbleItemSerials').get(0).options[$('#ddlAvailAbleItemSerials').get(0).options.length] = new Option(item.Display, item.Value);
                });
            },
            error: function () {
                alert("Connection Failed. Please Try Again.");
            }
        });

回答by Jakub Lok?a

If you still can't get it to work, try checking the page URLyou are calling the $.postfrom.

如果您仍然无法使其工作,请尝试检查您正在调用的页面 URL$.post

In my case I was calling this method from localhost:61965/Exampleand my code was:

在我的情况下,我正在调用这个方法localhost:61965/Example,我的代码是:

$.post('Api/Example/New', { jsonData: jsonData });

Firefox sent this request to localhost:61965/Example/Api/Example/New, which is why my request didn't work.

Firefox 将此请求发送到localhost:61965/Example/Api/Example/New,这就是我的请求无效的原因。