SignalIR and KnockoutJS in Asp.Net Web Form

2019-04-14 02:37发布

问题:

I seen may samples of SignalIR and KnockoutJS samples on MVC platform but not on WebForm. Please suggest me, can we use on WebForm? Any articles link would be appreciable.

回答1:

I know this is exactly a month late but here's a quick example [this is a trivial example that i have built from exploring MVC examples]

lets say u have a page called MyPage

in the .aspx file write the following:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.signalR-0.5.2.min.js" type="text/javascript"></script>
    <script type="text/javascript" src='<%= ResolveClientUrl("~/signalr/hubs") %>'></script>

    <script type="text/javascript">
        $(function () {
            var conChat = $.connection.chat;
            conChat.addMessage = function (message) {
                $('#disMess').append('<li>' + message + '</li>');
            };
            $("#btnSend").click(function () {
                conChat.send($('#txtMess').val());
                $('#txtMess').val('');
            });
            $.connection.hub.start();
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <ul id="disMess"></ul>
        <input id="txtMess" />
        <!-- see onclick also -->
        <input id="btnSend" type="button" value="Send" />
    </div>
    </form>
</body>
</html>

and actually nothing in the .cs file [or the code behind]

you'll need to add the ASP.NET folder "Add_Code" and place a class "Chat.cs" in it with the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SignalR.Hubs;

namespace NewSignalRChat
{
    public class Chat : Hub
    {
        public void Send(string msg)
        {
            Clients.addMessage(msg);
        }
    }
}


回答2:

SignalR hosting (server side) is implemented as AspNetHandler so there is not any dependency on mvc. SignalR client and KnockoutJs are javascript components without any dependency on mvc or web forms. Just use web methods for web forms instead of mvc's action methods.