如何将WebSocket数据从View发送到Controller,并将重新编写的数据发送到View with Ajax

时间:2017-03-04 21:45:51

标签: javascript c# asp.net json ajax

我正在尝试将websocket数据从视图发送到控制器,并再次将返回的数据发送到例如带有按钮或类似表格的表中查看。 现在将数据发送到控制器工作:

查看:



<script type="text/javascript">
    var webSocket;
    var webSocketValue;
    function webSocketResults() {
        webSocket = new WebSocket("ws://......");
        webSocket.onmessage = function (event) {
            webSocketValue = event.data;
            $("#webSocketValue").text(webSocketValue);
            $.ajax({
                url: "@Url.Action("getWebSocketResults", "Home")",
                type: "POST",
                contentType: "application/json",
                data: webSocketValue
            });
        };
        showCurrenciesData(webSocketValue);
    }
    function showCurrenciesData() {
        $.ajax({
            cache: false,
            type: "GET",
            url: "@Url.Action("getWebSocketResults", "Home")",
            dataType: 'json',
            success: function (result) {
                alert("Sukcess!!" + result);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('Failed to retrieve data.');
            }
        });
    }
    window.onload = webSocketResults;
&#13;
&#13;
&#13;

控制器

    public ActionResult getWebSocketResults(Currencies currencies)
    { //do something with data "currencies" and dynamicly send this to view
        var webSocketItems = currencies.items.ToList();
        return Json(webSocketItems, JsonRequestBehavior.AllowGet);
    }

在Controller中我有来自View的数据(对象)。 如何动态发送此数据。 WebSocket的新数据每分钟都会到达。 将数据发送到视图确实无效。

1 个答案:

答案 0 :(得分:1)

你打了两次电话。第一次没有处理结果。第二次没有参数。

<script type="text/javascript">
var webSocket;
var webSocketValue;
function webSocketResults() {
    webSocket = new WebSocket("ws://......");
    webSocket.onmessage = function (event) {
       showCurrenciesData(event.data);
    };

}
function showCurrenciesData(data) {
    $.ajax({
        cache: false,
        type: "GET",
        url: "@Url.Action("getWebSocketResults", "Home")",
        dataType: 'json',
        data: data,
        success: function (result) {
            alert("Sukcess!!" + result);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('Failed to retrieve data.');
        }
    });
}
window.onload = webSocketResults;