SignalIR and KnockoutJS in Asp.Net Web Form

◇◆丶佛笑我妖孽 提交于 2019-12-04 17:38:35

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!