【发布时间】:2013-03-19 05:58:33
【问题描述】:
我正在尝试使用 AJAX/Jquery 和 c# 写入我的数据库。每当我将参数传递给 C# 代码时,它都会显示为 null。我正在使用 Visual Studio 在创建控制器类时生成的默认模板。任何帮助将不胜感激!
注意:这是我试图调用的休息服务。 (一个普通的 ASP 网站......不是 MVC。此外,GET Rest api 工作得很好。)
jQuery/AJAX:
var dataJSON = { "name": "test" }
$('#testPostMethod').bind("click", GeneralPost);
function GeneralPost() {
$.ajax({
type: 'POST',
url: '../api/NewRecipe',
data:JSON.stringify(dataJSON),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
}
C#
//If I remove the [FromBody] Tag then when I click the button this method is never called.
public void Post([FromBody]string name)
{
}
编辑:
我已经稍微调整了我的代码,但仍然遇到同样的问题。回顾一下,它正在加载 POST 方法,但它传入的是 null。
C#
public class RecipeInformation
{
public string name { get; set; }
}
public void Post(RecipeInformation information)
{
}
AJAX:
var dataJSON = { information: { name: "test" } };
$('#testPostMethod').bind("click", GeneralPost);
console.log(dataJSON);
function GeneralPost() {
$.ajax({
type: 'POST',
url: '../api/NewRecipe',
data: dataJSON,
contentType: 'application/json; charset=utf-8',
});
}
【问题讨论】:
-
Post(string name)是 MVC 应用程序、Web 服务还是什么的一部分? -
抱歉,这是 ASP - 一个 Rest 服务。 GET 完美运行。
-
@Yecats 你的 [WebMethod] 属性和静态关键字在哪里使该方法可用?
标签: c# jquery ajax asp.net-web-api