[英]ASP.NET Core Post Action returns null
I have a simple controller method that should return a JSON result but returns null. 我有一个简单的控制器方法,应该返回JSON结果,但返回null。 I need to call it using jQuery $.ajax
. 我需要使用jQuery $.ajax
来调用它。 I tested it using Postman and it does return null. 我使用Postman对其进行了测试,但它确实返回null。 I am not sure what I am doing wrong. 我不确定自己在做什么错。
I tested it with Postman using the following JSON data and it returns null: 我使用以下JSON数据与Postman进行了测试,结果返回null:
{ "id": 2 }
Here is the controller method: 这是控制器方法:
// Post: Contact
[HttpPost, ActionName("GetContact")]
public JsonResult GetContactPost([FromBody] long id)
{
var contact = _context.Contact.SingleOrDefault(m => m.ContactId == id);
return Json(contact);
}
In my application I am using the following JavaScript and it returns null as well: 在我的应用程序中,我使用以下JavaScript,它也返回null:
function GetContact(id) {
$.ajax({
type: "POST",
url: "@Url.Action("GetContact","Contacts")",
data: { id: id },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("id: " + id + " result: " + result);
},
failure: function (response) {
alert(response.d);
}
});
}
I figured it out. 我想到了。 The parameter has to be a model or view model object. 参数必须是模型或视图模型对象。
// Post: Contact
[HttpPost, ActionName("GetContact")]
public JsonResult GetContactPost([FromBody] ContactVM findContact)
{
var contact = _context.Contact.SingleOrDefault(m => m.ContactId == findContact.Id);
return Json(contact);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.