[英]Passing JSON to WebApi in MVC5
im facing issues in syntax to pass json array from jquery to the webapi in my mvc5 project . 我面临语法问题,将jQuery数组从jquery传递到我的mvc5项目中的webapi。
Following is my code :- 以下是我的代码:-
C# code:- C#代码:-
//GET Instance //获取实例
// GET: api/PostDatas
public IQueryable<PostData> GetPostDatas()
{
return db.PostDatas;
}
//POST Instance // POST实例
// POST: api/PostDatas
[ResponseType(typeof(PostData))]
public IHttpActionResult PostPostData(PostData postData)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.PostDatas.Add(postData);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = postData.postDataID }, postData);
}
JQuery JQuery的
<script>
function fnpostdata() {
var model = {
"userid": "01",
"Description": "Desc",
"photoid": "03"
};
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/api/PostDatas/",
data: model,
success: function (data) {
alert('success');
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
}
</script>
Im not able to send the data using jquery to my c# controller , just need to understand the syntax . 我无法使用jquery将数据发送到我的c#控制器,仅需要了解语法。 Thank you . 谢谢 。
check following things in your code: 1) Method attribute [HttpPost] 2) [FromBody] for input model 3) Check PostData class, it should contain public properties for userid, Description and photoid with case-sensitive of variable names. 检查代码中的以下内容:1)方法属性[HttpPost] 2)[FromBody]用于输入模型3)检查PostData类,它应包含userid,Description和photoid的公共属性,且变量名区分大小写。
and mainly change your AJAX request code to: 并将您的AJAX请求代码主要更改为:
function fnpostdata() {
var model = {
"userid": "01",
"Description": "Desc",
"photoid": "03"
};
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/api/PostDatas/",
data: JSON.stringify(model), //i have added JSON.stringify here
success: function (data) {
alert('success');
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
}
Please let me know, is this works for you? 请让我知道,这对您有用吗?
I included [FromBody]
in the parameter in my previous project. 我在上一个项目的参数中包含了[FromBody]
。 Something like this: 像这样:
[HttpPost]
public IHttpActionResult Register([FromBody]PostData postData)
{
// some codes here
}
I was able to read the JSON data from that notation. 我能够从该表示法读取JSON数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.