Action method return raw json data instead of view in ASP.NET Core 2.2

前端 未结 1 855
暖寄归人
暖寄归人 2021-01-29 01:30

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

            


        
相关标签:
1条回答
  • 2021-01-29 01:43

    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):

    0 讨论(0)
提交回复
热议问题