I have gone through this solution on stackoverflow but I couldn't solve my problem.
In HomeController I have a method named as Audit which I want to be posted from /Home/Index page's script through jQuery. 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:
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. I think there is problem either in controller or, in $.post method. 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.
$.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
[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");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.