AJAX - 将JSON发布到控制器ASP.NET MVC

时间:2017-06-21 19:38:45

标签: ajax asp.net-mvc

我正在尝试调用已弃用的Google财经API(只是为了学习)解析响应并将其发布到我的控制器。我向用户显示一个0值的视图但是一旦响应返回,我将显示解析的结果。

除了将视图打印到控制台而不是显示之外,结果看起来很完美。我在这里俯瞰什么?任何其他反馈也欢迎,因为我只是想学习ASP.NET MVC。

这是我的代码:

HomeController中:

    public ActionResult Index3()
    {
        var model = from a in realList orderby a.Symbol select a;

        return View(model);
    }

    [HttpPost]
    public ActionResult Index3(string JSON)
    {
        // parse response...
        // listOfStocks.Add(...);

        var model = from a in listOfStocks orderby a.Symbol select a;

        return View(model);
    }

    static List<Stocks> listOfStocks = new List<Stocks>();

INDEX3:

@model IEnumerable<WebApplication2.Models.Stocks>

@{
    ViewBag.Title = "Stock Texter";
}
<h2>Stock List</h2>


<table class="table table-striped">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Symbol)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Change)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ChangePercent)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.PreviousClose)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Symbol)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Change)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ChangePercent)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.PreviousClose)
            </td>
        </tr>
    }
</table>


@section JavaScript
{
    <script src="@Url.Content("/Scripts/test.js")"></script>
}

test.js:

(function ($, window, document) {
    var data = "";
    $.when(
        $.getJSON("http://finance.google.com/finance/info?client=ig&q=NASDAQ%3AAAPL,JPM,CAT,MSFT&callback=?", function (response) {
            data = response;
            console.log("call succcessful");
        })
    ).then(function () {
        $.ajax({
            type: "POST",
            url: "/home/index3",
            data: { 'JSON': JSON.stringify(data) },
            success: function (response2) {
                console.log(response2);
            }
        });
    });
}(window.jQuery, window, document));

2 个答案:

答案 0 :(得分:2)

因为您当前的代码正在success事件中将响应从ajax调用记录到控制台。

理想情况下,您应该返回从ajax调用中显示表所需的标记。因此,最好将其移至我们可以重复使用的局部视图。创建一个名为“Results.cshtml”的局部视图,并移动代码以在那里呈现表格。

这里我只是使用p标签而不是编写所有代码来呈现表格。您可以使用此处的问题替换原始代码(需要呈现表格)

@model IEnumerable<WebApplication2.Models.Stocks>
@foreach (var item in Model)
{
  <p>@item.Symbol</p>
  <!-- You can change this table rendering code as you have in the question. -->
}

现在在主视图(Index3.cshtml)中调用此部分视图以获取初始页面加载。将调用包装到容器div中的局部视图

@model IEnumerable<WebApplication2.Models.Stocks>
@{
    ViewBag.Title = "Stock Texter";
}
<h2>Stock List</h2>
<div id="resultContainer">
  @Html.Partial("Results",Model)
</div>

现在进行ajax调用,仅返回此部分视图

[HttpPost]
public ActionResult Index3(string JSON)
{
    //  to do : Your code
    var model = from a in listOfStocks orderby a.Symbol select a;

    return PartialView("Results",model);
}

现在在ajax调用的成功事件中,不是写入控制台,而是更新容器div。

success: function (response2) {
            $("#resultContainer").html(response2);
        }

答案 1 :(得分:0)

请查看我的回答以帮助解决您的问题。如果您希望我查看更多答案,请告诉我。

查看:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index59</title>
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btn").click(function (ev) {
                (function ($, window, document) {
                    var data = "";
                    $.when(
                        $.getJSON("http://finance.google.com/finance/info?client=ig&q=NASDAQ%3AAAPL,JPM,CAT,MSFT&callback=?", function (response) {
                            data = response;
                            console.log("call succcessful");
                        })
                    ).then(function () {
                        alert(JSON.stringify(data))
                        $.ajax({
                            type: "POST",
                            url: "/Home/GetData",
                            data: { 'JSON': JSON.stringify(data) },
                            success: function (response2) {
                                var ap = "dh";
                                //You have to manually assign each value or use a partial view
                                var theArr = JSON.parse(response2);
                                var apdg = "dh";
                                jQuery.each(theArr, function (index, value) {
                                    //selecting all rows, just selecting two fields
                                    $("#theData").append(" e=" + value.e + " ltt=" + value.ltt)
                                    //you would set the field based on id
                                    //$("#MyField").val(value.ltt)
                                });
                            }
                        });
                    });
                }(window.jQuery, window, document));
            })
        })
    </script>
</head>
<body>
    <div id="theData"></div>
    <input type="button" value="GetData" id="btn" />
</body>
</html>

控制器:

   public string GetData(string JSON)
    {
        return JSON;
    }