使用 jQuery $.ajax() 和 $.post() 将字符串数据发送到 MVC 控制器 [英] Sending String Data to MVC Controller using jQuery $.ajax() and $.post()

查看:21
本文介绍了使用 jQuery $.ajax() 和 $.post() 将字符串数据发送到 MVC 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

这是我试过的ajax方法:

And here is the ajax method I tried:

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

这是我的控制器:

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

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

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?

非常感谢.

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

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("/Journal/SaveEntry", { "jsonData": JSONstring });

推荐答案

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

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:

public void SaveEntry(string jsonData)

我在 JS 中的 post action 看起来像:

and my post action in JS looks like:

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

JSONstring 是我使用 JSON 插件 由 json.org 提供.所以:

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

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

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

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.

这篇关于使用 jQuery $.ajax() 和 $.post() 将字符串数据发送到 MVC 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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