【问题标题】:How to return json object and view tgt from mvc controller如何从 mvc 控制器返回 json 对象并查看 tgt
【发布时间】:2020-11-18 20:10:34
【问题描述】:

我正在做一个 MVC 应用程序,我需要将 json 对象从控制器传递到视图。

 public ActionResult VisualizeResult(int? id)
        {
            using (var context = new DBQUIZEntities())
            {
                context.Configuration.LazyLoadingEnabled = false;
                List<Choices> stdResult = context.Choices.Where(x => x.QuestionID == id).ToList();
                return Json(stdResult, JsonRequestBehavior.AllowGet);
            }
        }

当我将数据传递到此视图并打开它时,我在控制器中使用了上述代码。它返回我一个 json 字符串。(我理解因为没有返回视图,所以它返回一个 json 但如果我将其更改为查看)就像我不知道如何在我的视图函数中使用这些数据。

  List<Choices> stdResult = context.Choices.Where(x => x.QuestionID == id).ToList();
                // return Json(stdResult, JsonRequestBehavior.AllowGet);
                return View(stdResult);

我的看法

<head>
    <title>Result Visualization</title>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <script>
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                url: '@Url.Action("VisualizeResult", "Home")',
                success: function (result) {
                    google.charts.load('current', {
                        'packages': ['corechart']
                    });
                    google.charts.setOnLoadCallback(function () {
                        drawChart(result);
                    });
                }
            });
        });

        function drawChart(result) {
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Name');
            data.addColumn('number', 'Vote');
            var dataArray = [];


            $.each(result, function (i, obj) {
                dataArray.push([obj.ChoiceText, obj.VoteCount]);
            });
            data.addRows(dataArray);

            var columnChartOptions = {

                width: 1000,
                height: 400,
                bar: { groupWidth: "20%" },
            };

            var columnChart = new google.visualization.PieChart(document
                .getElementById('piechart_div'));

            columnChart.draw(data, columnChartOptions);
        }
    </script>
</head>

现在我想用这个 json 字符串返回我的视图页面,我该如何通过更改视图或控制器来做到这一点。 我的目标是在谷歌图表中显示结果。

【问题讨论】:

  • 你想要页面呈现服务器端还是你想通过异步ajax消费json?
  • 如果你在回调中使用console.log(result),它会记录数据吗?
  • 我不使用.net,但你不能使用两个,一个返回json,另一个返回视图。然后调用从另一个返回 json 的那个?另外,我建议先加载 google,然后调用 ajax,这样您就可以多次调用 ajax 而无需重新加载页面。您可以使用 google 的 load 语句代替 jquery 的 ready 语句。查看this answer中的设置...
  • 我确实尝试使用两个,但失败了。也许是因为我不知道如何在脚本@WhiteHat 中传递数据
  • @Vince 我不明白你的意思,对不起,我是 javascript 新手。如果使用第一个控制器,它确实通过了 json。但没有视图

标签: json asp.net-mvc asp.net-mvc-4 model-view-controller google-visualization


【解决方案1】:

你可以这样做

  1. 首页/索引将返回视图,您可以相应地设置您的路由器
  2. Home/VisualizeResult 将在 ajax 调用中返回 json 数据
public ActionResult Index(int? id)
        {
            return view("chart");
        }
        public ActionResult VisualizeResult(int? id)
        {
            List<Choices> stdResult = GetResult(id, ref context);
            return Json(stdResult, JsonRequestBehavior.AllowGet);
        }

        private static List<Choices> GetResult(int? id, ref DBQUIZEntities context)
        {
            using (var context = new DBQUIZEntities())
            {
                context.Configuration.LazyLoadingEnabled = false;
                List<Choices> stdResult = context.Choices.Where(x => x.QuestionID == id).ToList();
                return stdResult;
            }
        }

【讨论】:

  • 谢谢你的回答,但是我如何通过按钮传递数据 查看结果是这样的吗?
  • 你可以这样传递:&lt;a class="btn btn-info btn-sm" href="@Url.Action("Index", "Home", new { id=question.QuestionID})"&gt;View Result&lt;/a&gt; 或者配置路由,App_Start >> RouteConfig.cs
  • 它返回一个没有图表视图的 json [{"Questions":null,"ChoiceID":1,"ChoiceText":"a for question1","QuestionID":1,"VoteCount": 9,"TextAns":null,"Rating":null,"ThisDateTime":null},{"Questions":null,"ChoiceID":2,"ChoiceText":"b for question 1","QuestionID":1 ,"VoteCount":5,"TextAns":null,"Rating":null,"ThisDateTime":null}]
  • 查看顶部的代码我只是复制并粘贴到主视图中
  • 好的,据我了解,您想第一次加载“顶部的 myview 代码”,然后单击按钮想通过获取数据来加载图表?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多