我試圖打電話給不贊成的Google Finance API(只是爲了解)解析響應並將其發佈到我的控制器。我向用戶顯示具有0值的視圖,但是一旦響應返回,我將顯示解析的結果。AJAX - 發佈JSON到控制器ASP.NET MVC
除了將視圖打印到控制檯而不是顯示之外,結果看起來很完美。我在這裏忽略了什麼?任何其他反饋也歡迎,因爲我只是想學習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));
這做到了,非常感謝! – user94614