问题
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.
My action method
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:
$.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>' }
},
}
]
})
}
})
What it returns:
instead of a view.
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
回答1:
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="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/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:
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(the url should be:/home/index):
来源:https://stackoverflow.com/questions/59447189/action-method-return-raw-json-data-instead-of-view-in-asp-net-core-2-2