本文介绍了动作方法返回原始json数据而不是ASP.NET Core 2.2中的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从数据库中获取数据并以JSON的形式发送以进行查看以填充数据表,但是操作方法返回了原始JSON数据.
I want to get data from the database and send it as JSON to view to fill datatable with it, but action method returns raw JSON data.
我的动作方法
public IActionResult GoodsList() { var goodsScale = (from g in context.Goods join s in context.Scale on g.ScaleId equals s.Id select new { id = g.Id, goodsName = g.Name, scale = s.ScaleName }); return Json(goodsScale); }jQuery ajax:
jQuery ajax:
$.ajax({ type: 'GET', dataType: 'JSON' url: '@Url.Action("GoodsList", "Goods")', success: function (data) { console.log("Data:", data); $('#datatable').DataTable({ data: response, columns: [ { 'data': 'id' }, { 'data': 'goodsName' }, { 'data': 'scale' }, { 'data': 'id', 'render': function (data) { { return '<a href="#" title="ویرایش" style="margin-left:10px" class="btn btn-success button" onclick="openModal(' + data + ');"><i class="fa fa-edit"></i></a><a href="#" title="حذف" style="margin-right:10px" class="btn btn-danger button" onclick="deleteUser(' + data + ')"><i class="fa fa-trash"></i></a>' } }, } ] }) } })返回的内容:
代替视图.
我应该提到的是,我在应用程序的另一个位置使用了相同的过程,它可以正常工作,但是我不知道这个过程有什么问题
I should mention that I used the same procedure in another place in my app and it works fine but I have no idea what is wrong with this one
推荐答案下面是一个工作示例,如下所示:
Here is a working demo like below:
1.View( Index.cshtml ):
<table id="datatable" class="display" style="width:100%"> <thead> <tr> <th>id</th> <th>goodsName</th> <th>scale</th> <th>action</th> </tr> </thead> <tfoot> <tr> <th>id</th> <th>goodsName</th> <th>scale</th> <th>action</th> </tr> </tfoot> </table> @section Scripts{ <link rel="stylesheet" type="text/css" href="cdn.datatables/1.10.20/css/jquery.dataTables.css"> <script type="text/javascript" charset="utf8" src="cdn.datatables/1.10.20/js/jquery.dataTables.js"></script> <script> $(document).ready(function () { $('#datatable').DataTable({ ajax: { type: 'GET', dataType: 'JSON', url: '@Url.Action("GoodsList", "Home")' }, columns: [ { 'data': 'id' }, { 'data': 'goodsName' }, { 'data': 'scale' }, { 'data': 'id', 'render': function (data) { { return '<a href="#" title="ویرایش" style="margin-left:10px" class="btn btn-success button" onclick="openModal(' + data + ');"><i class="fa fa-edit"></i></a><a href="#" title="حذف" style="margin-right:10px" class="btn btn-danger button" onclick="deleteUser(' + data + ')"><i class="fa fa-trash"></i></a>' } }, } ] }) }) </script> }2.Controller:
2.Controller:
public IActionResult Index() { return View(); } public IActionResult GoodsList() { var goodsScale = new List<object> { new {id = 1, goodsName= "aa",scale="a"}, new {id = 2, goodsName= "bb",scale="b"}, new {id = 3, goodsName= "cc",scale="c"}, new {id = 4, goodsName= "dd",scale="d"} }; return Json(new { data=goodsScale }); }3.Result(网址应为:/home/index ):
3.Result(the url should be:/home/index):
更多推荐
动作方法返回原始json数据而不是ASP.NET Core 2.2中的视图
发布评论