[英]How to retrieve JSON data in controller in ASP.net Core?
i need to get data sent with JSON and save to model in asp.net controller我需要使用 JSON 发送数据并保存到 asp.net 控制器中的模型
//JSON data
var dataType = 'application/json';
var data = {
ID: 'Zaki',
}
console.log('Submitting form...');
console.log(data);
$.ajax({
type: 'POST',
url: 'Save',
dataType: 'json',
contentType: dataType,
data: data,
success: function (result) {
console.log('Data received: ');
console.log(result);
}
});
Controller控制器
[HttpPost]
public ActionResult Save([FromBody] string ID)
{
return Json (ID);
}
am getting null in console , it supposed to be zaki and from there i wanna write saving code...我在控制台中变空了,它应该是 zaki 并且从那里我想编写保存代码...
Another way to do it is to simply use 'dynamic' type to handle json request data.另一种方法是简单地使用“动态”类型来处理 json 请求数据。 Take a look:看一看:
[HttpPost]
public IActionResult YoutMethod([FromBody] dynamic requestData)
{
Log.Information(requestData.field1);
Log.Information(requestData.field2);
// ...
return Ok();
}
Modify this line in your code data: data, to 修改代码数据中的这一行:数据,以
data:JSON.stringify(data) 数据:JSON.stringify(数据)
When sending data to a web server, the data has to be a string and JSON.stringify method converts a JavaScript object into a string. 将数据发送到Web服务器时,数据必须是字符串,并且JSON.stringify方法将JavaScript对象转换为字符串。
Another approach would be, instead of getting raw string value, wrap your parameter into a class object like this 另一种方法是,不要获取原始字符串值,而是将参数包装到这样的类对象中
public class ParamObj
{
public string ID{get;set;}
}
and in your controller get a parameter of this object type like this.. 并在您的控制器中获得像这样的对象类型的参数。
public ActionResult Save([FromBody] ParamObj data)
Thanx 感谢名单
I know that is already marked as answered, but here is another way to do it: 我知道已经将其标记为已回答,但这是另一种方法:
I am not using the binding FromBody attribute. 我没有使用绑定的FromBody属性。
Controller 调节器
public class JsonRequest
{
public string Id { get; set; }
}
[HttpPost]
public ActionResult Save(JsonRequest data)
{
return Json(data.Id);
}
Instead of using dataType I am using accept and you don't need to convert your json into a string. 而不是使用dataType,而是使用accept ,您不需要将json转换为字符串。
To avoid problems with relative paths I am using: url: '@Url.Action("Save", "Home")' as well. 为了避免相对路径出现问题,我也在使用:url:'@ Url.Action(“ Save”,“ Home”)'。
Javascript 使用Javascript
function send()
{
//JSON data
var dataType = 'application/json';
var data = {
"id": "Zaki"
}
console.log('Submitting form...');
console.log(data);
$.ajax({
type: 'POST',
url: '@Url.Action("Save", "Home")',
accept: dataType,
data: data,
success: function (result) {
console.log('Data received: ');
console.log(result);
}
});
}
Good luck with your project. 祝您项目顺利。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.