如何将控制器中的`json`数据传递给View并使用它来形成表?

问题描述 投票:0回答:1

[我试图通过Ajax将列表作为json字符串从Controller传递到View,并希望以表格式显示json字符串,但我只是在View中获得普通的json字符串。

Contoller Code

[HttpGet]
        public JsonResult GetRegRequests()
        {
            var model = new TaskManagementEntities().RegRequests.ToList();
            return Json(model,JsonRequestBehavior.AllowGet);
        }

这里是视角。

 <div id="showRequest">
        <table class="table-responsive reqtab">
            <thead class="thead-dark">
            <th>Req ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>User Name</th>
            <th>Password</th>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>

和脚本标签

<script>
    $.ajax({
        cache: false,
        type: 'GET',
        url: @Url.Action("MasterAdmin", "Index"),
        dataType: 'json',
        success:
            function (result) {
                console.log(result);
                $(".reqtab tbody").append("<tr><td>" + result.first_name + "</td><td>" + result.last_name + "</td><td>" + result.user_name +"</td><td>"+ result.password+"</td></tr>")
            }
    })
</script>

我也没有得到表头,而是得到了简单的json数据,并且浏览器控制台显示以下错误。我不确定是否与该错误有关。

jquery.unobtrusive-ajax.min.js:16 Uncaught ReferenceError: jQuery is not defined
at jquery.unobtrusive-ajax.min.js:16

我如何将这个json字符串传递给View并使用它形成表格?

json ajax asp.net-mvc asp.net-ajax
1个回答
0
投票

您忘记了包含JQuery插件,这就是为什么控制台显示您需要未定义jQuery的原因。

在html中添加脚本:

<script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>
© www.soinside.com 2019 - 2024. All rights reserved.