user94614
user94614

Reputation: 521

AJAX - posting JSON to controller ASP.NET MVC

I'm attempting to make a call to the deprecated Google Finance API (just to learn) parsing the response and post it to my controller. I show the user a view with 0 values but once the response returns, I will display the parsed results.

The results look perfect except that the view is printed to the console instead of being displayed. What am I overlooking here? Any other feedback is also welcome as I'm just trying to learn ASP.NET MVC.

Here is my code:

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

Upvotes: 1

Views: 1432

Answers (2)

kblau
kblau

Reputation: 2107

Please review my answer to help with your question. If you want me to look into more answers, please let me know.

View:

<!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>

Controller:

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

Upvotes: 0

Shyju
Shyju

Reputation: 218942

Because your current code is logging the response from ajax call to the console in the success event.

Ideally you should return the markup needed to display the table from your ajax call. So it is better to move that to a partial view which we can re use. Create a partial view called "Results.cshtml" and move the code to render the table there.

Here i am simply using the p tag instead of writing all the code to render the table. You may replace with your original code (needed to render the table) from the question here

@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. -->
}

Now call this partial view in your main view(Index3.cshtml) for the initial page load. Wrap the call to the partial view in a container div

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

Now for your ajax call, return this partial view only

[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);
}

Now in the ajax call's success event, instead of writing to the console, update the container div.

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

Upvotes: 2

Related Questions