我正在尝试使用AJAX / Jquery和c#来写入我的数据库。每当我将参数传递给C#代码时,它都显示为null。我使用的是visual studio在创建控制器类时生成的默认模板。任何帮助都将不胜感激!
NOte:这是我正在尝试调用的rest服务。(一个常规的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',
});
}
发布于 2013-03-29 17:13:47
对于简单类型,在服务器端:
public void Post([FromBody]string name)
{
}
在客户端,您只需定义是否要以json格式发送:
var dataJSON = "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'
});
}
如果你想让它在复杂类型中工作,你应该从服务器端定义:
public class RecipeInformation
{
public string name { get; set; }
}
public class ValuesController : ApiController
{
public void Post(RecipeInformation information)
{
}
}
而在客户端:
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'
});
}
发布于 2013-03-29 05:50:56
您可以尝试这样做,并使用jquery param方法
var postData = {
name : 'name'
}
$('#testPostMethod').bind("click", GeneralPost);
function GeneralPost() {
$.ajax({
type: 'POST',
url: '../api/NewRecipe',
data: $.param(postData,true),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
}
发布于 2013-03-29 05:05:34
如果你创建一个这样的类,你会遗漏一个数据契约属性:
[DataContract]
public class RecipeInformation
{
[DataMember]
public string name { get; set; }
}
这些属性可以在System.Runtime.Serialization中找到,Json解析器(Json.NET)使用它们来(帮助)反序列化模型。
https://stackoverflow.com/questions/15687903
复制相似问题