【问题标题】:How can I Pass `json` Data from controller to View and use that to form a table?如何将“json”数据从控制器传递到 View 并使用它来形成表格?
【发布时间】:2020-05-03 17:14:53
【问题描述】:

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

控制器代码

[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 并使用它来形成表格?

【问题讨论】:

  • 你应该在 jquery.unobtrusive 之前加载 jquery.js。

标签: json ajax asp.net-mvc asp.net-ajax


【解决方案1】:

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

在您的 html 中 jquery.unobtrusive 之前添加脚本:

<script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>

另外,你返回的ajax结果是List(array)类型,如果你想显示所有数据,你必须为每个他们。否则,您将获得 undefined 值。

代码:

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

【讨论】:

    猜你喜欢
    • 2013-05-09
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多