AJAX和Web Api Post方法 – 它是如何工作的?
我正在尝试使用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', }); }
对于简单类型,在服务器端:
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' }); }
你可以尝试做这样的事情并使用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' }); }
我假设您正在使用ASP.NET WebAPI并且它绑定了URL中的所有简单类型(int,bool,string等)以及来自body的所有复杂类型。 当您使用FromBody
属性标记名称时,它会从请求正文而不是url映射绑定它。
您可以在此处阅读有关ASP.NET WebAPI路由和参数绑定的更多信息:
- 在www.asp.net上
- 在www.west-wind.com上
- 在MSDN上
API控制器中的绑定有点奇怪。 我相信:
public void Post([FromBody]RecipeInformation information)
同
var dataJSON = { name: "test" };
应该工作,如果你只是作为表单数据传递它肯定会工作。
有一件你缺少的是数据合同属性如果你让你的class级像:
[DataContract] public class RecipeInformation { [DataMember] public string name { get; set; } }
这些属性可在System.Runtime.Serialization中找到,Json解析器(Json.NET)使用它们来帮助(帮助)反序列化模型。
我在上面提到的Microsoft Docs Use JS代码的帮助下发现了这个问题
$.post('api/updates/simple', { "": $('#status1').val() });
我错过了添加空属性名称,所以OP需要做的是{"":data:JSON.stringify(dataJSON)},
而不是data:JSON.stringify(dataJSON),