发送字符串数据MVC控制器使用jQuery $阿贾克斯()和$。员额() [英] Sending String Data to MVC Controller using jQuery $.ajax() and $.post()

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

问题描述

有一定是我丢失的东西。我已经使用$阿贾克斯()和$。员额()将字符串发送到我的ASP.NET MVC控制器试过了,当正在达到控制器,该字符串为空,当它到达那里。因此,这里是POST方法我试过:

  $后(/期刊/ SaveEntry,JSONstring)。

这里是我试过的AJAX方法:

  $。阿贾克斯({
网址:/期刊/ SaveEntry
键入:POST,
数据:JSONstring
});

下面是我的控制器:

 公共无效SaveEntry(字符串数据)
{
串somethingElse =数据;
}

有关背景,我系列化透过JSON.stringify()一个JSON对象,这是成功的。我试图将它发送给我的控制器反序列化()它。但正如我所说,该字符串到达​​为空各一次。任何想法?

非常感谢。

更新:有人回答我的问题是,我是没有使用键/值对作为参数传递给$。员额()。所以,我想这一点,但仍串到达控制器为空:

  $后(/期刊/ SaveEntry,{jsonData:JSONstring});


解决方案

回答。我没有足够的变量名称我的第一次更新后设置正确。我在控制器中jsonData改变变量名,所以我的新控制器的头看起来像:

 公共无效SaveEntry(字符串jsonData)

和JS在我的岗位操作是这样的:

  $后(/期刊/ SaveEntry,{jsonData:JSONstring});

JSONstring是字符串化(或序列化)的JSON序列化我使用的 JSON插件就职于json.org提供。所以:

  JSONstring = JSON.stringify(JournalEntry的); // JournalEntry的是我的JSON对象

因此​​,在$ .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);

And here is the ajax method I tried:

$.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?

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

解决方案

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)

and my post action in JS looks like:

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

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

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.

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

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