[英]Problem with jQuery post to ASP.NET Core controller
I have gone through this solution on stackoverflow but I couldn't solve my problem. 我已经通过了关于stackoverflow的解决方案 ,但无法解决我的问题。
In HomeController I have a method named as Audit which I want to be posted from /Home/Index page's script through jQuery. 在HomeController中,我有一个名为Audit的方法,我想通过jQuery从/ Home / Index页面的脚本中发布该方法。 The controller looks like:
控制器看起来像:
public class HomeController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Audit([FromBody] JObject jObject)
{
if (jObject != null)
{
return Json("success");
}
return Json("failed");
}
}
In the /Home/Index pages's javascript file I have tried to post a JSON Object to that Audit in a way like this: 在/ Home / Index页面的javascript文件中,我试图以这种方式将JSON对象发布到该Audit:
var auditData = {};
$(document).ready(function(){
var request = $.getJSON('http://www.geoplugin.net/json.gp', function (responseData, status) {
auditData = {
Latitude : responseData.geoplugin_latitude,
Longitude : responseData.geoplugin_longitude
};
$.post('Audit', auditData, function (response) {
console.log(response);
});
});
});
I want the auditData object to be posted as JObject in /Home/Audit but something is going wrong. 我希望将auditData对象作为JObject发布在/ Home / Audit中,但是出了点问题。 I think there is problem either in controller or, in $.post method.
我认为控制器或$ .post方法中都有问题。 How can I solve this problem?
我怎么解决这个问题?
Your post URL is wrong, and you need to name the data you're posting back as jObject
as well to match what you defined in your controller. 您的发布URL错误,您还需要将要发布回的数据命名为
jObject
,以匹配您在控制器中定义的数据。
$.post('@Url.Action("audit", "home", new { area = "" })', { jObject: auditData },
function (response) {
console.log(response);
});
There are multiple issues in your current code, check points below one by one: 您当前的代码中存在多个问题,请逐一检查以下要点:
Home/Audit
Home/Audit
[ValidateAntiForgeryToken]
[ValidateAntiForgeryToken]
Code: 码:
Client 客户
@section Scripts{
<script type="text/javascript">
var auditData = {};
$(document).ready(function(){
auditData = {
Latitude : "l1",
Longitude : "l2"
};
$.ajax({
type: 'POST',
url: 'Home/Audit',
data: JSON.stringify(auditData),
success: function(data) { alert('data: ' + data); },
contentType: "application/json"
});
});
</script>
}
Server: 服务器:
public class HomeController : Controller
{
[HttpPost]
//[ValidateAntiForgeryToken]
public JsonResult Audit([FromBody]JObject jObject)
{
if (jObject != null)
{
return Json("success");
}
return Json("failed");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.