我们正在尝试向我们的 Core Web API 发出 Ajax 请求,并将data
Json 结果返回给 Controller 进行进一步处理,其中包括 Json 对象结果的反序列化,Ajax 请求工作正常,我们能够获得所需的 Json 数据在data
。
这里的任何人都可以请建议更改或替代方案来实现这一目标吗?
查看(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>
}
控制器.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,但仍然无法获得结果集。请检查屏幕截图和下面的代码..
阿贾克斯请求:
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");
}
错误快照:
1) 添加 [FromBody] 您要返回的控制器。这将使控制器期望一个 JSON 对象。
[HttpPost]
public ActionResult Index([FromBody]RootObject model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
//return View("Index");
}
2)如果这不起作用,您没有发布正确的 json 对象/您没有发布 json 对象,用于console.dir(EventJson);
检查您在浏览器控制台中传递的对象。
3)如何在JS中创建JSON对象:https : //www.w3schools.com/js/js_json_stringify.asp
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句