我們正在嘗試向我們的Core Web API發出Ajax請求,並將JSON結果返回給Controller進行進一步處理,其中包括Json對象反序列化結果,Ajax請求工作正常,並且我們能夠獲得要求Json的數據在data
。如何將Ajax Json對象傳遞給.Net Core中的Controller類?
任何人都可以在這裏請建議的變化或替代品來實現這一目標嗎?
視圖(AJAX請求)
@section scripts
{
<script type="text/javascript">
$(document).ready(function() {
GetEventDetails('@Url.Content("~/")');
});
function GetEventDetails(contextRoot) {
$.ajax({
type: "GET",
url: contextRoot + "api/EventsAPI",
dataType: "json",
success: function (data) {
debugger;
var datavalue = data;
contentType: "application/json";
//Send data to controller ???
console.log(data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
</script>
}
Controller.cs
public ActionResult Index()
{
/*Do all stuff before returning view
1. Get Json Data from Ajax request
2. Deserialize the obtained Json Data
3. return to view
*/
return View("Index");
}
更新:
我試圖通過@J給出的解決方案。 Doe,但仍然無法獲得結果集。請檢查的截圖和代碼如下..
Ajax請求:
function GetEventDetails(contextRoot) {
$.ajax({
type: "GET",
url: contextRoot + "api/EventsAPI",
dataType: "json",
success: function (data) {
debugger;
var datavalue = data;
contentType: "application/json; charset=utf-8";
console.log(data);
var EventJson = data;
console.log(EventJson);
$.ajax({
type: "POST",
url: "@Url.Action("Index")",
dataType: "json",
data: EventJson,
contentType: "application/json; charset=utf-8",
//data: EventJson,
success: function (data) {
alert(data.responseText);
console.log('Data received: ');
console.log(data.responseText);
},
failure: function (errMsg) {
console.log(errMsg);
}
});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
類屬性:
public class RootObject
{
public Embedded _embedded { get; set; }
public Links _links { get; set; }
public Page page { get; set; }
}
下面是操作結果控制器:
public ActionResult Index(RootObject model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
//return View("Index");
}
錯誤快照:
請檢查更新的問題。 –