SignalR + MVC 4 Web application

Source: Internet
Author: User
Tags hasownproperty

In the previous section, we have initially learned about SignalR, which we will do in a SignalR Demon, with the following steps:

1. Create an MVC 4 Web application and select Basic

2. Create a Home controller, once created, the directory should look like this:

3. In the project, right-click the NuGet Program Management Pack, enter a string such as SIGNALR in the NuGet Program Management Pack to search, select Microsoft ASP. SIGNALR This project in the search results, and tap install

4. Add an Index Action to the newly created Home controller and create the view with the complete code for the view as follows:

<body> <div class= "container" > <input type= "text" id= "message" id= "message"/> <inpu T type= "button" id= "SendMessage" value= "Send"/> <input type= "hidden" id= "displayname"/> <ul ID = "discussion" ></ul> </div> <script src= "/scripts/jquery-1.8.2.min.js" ></script> &LT;SC Ript src= "/scripts/jquery.signalr-2.1.2.min.js" ></script> <script src= "Signalr/hubs" > </script > <script type= "Text/javascript" > $ (function () {//define a proxy to refer to Hub var chat = $            . Connection.chathub;            Defines the client-side JavaScript function for the server-side hub, which invokes all clients JavaScript function//Enter the name of the person in the dialog box via dynamic mode.            $ (' #displayname '). Val (Prompt (' Enter your Name: ', '));            Create a function so that the HUB can broadcast messages.  Chat.client.broadcastMessage = function (name, message) {//HTML-encoded for string var encodedname = $ (' #displayName '). Text (name). HTML ();                var encodedmsg = $ (' #message '). Text (message). HTML ();            Append and display the chat information in the page $ (' #discussion '). Append (' * ' + encodedname + ': ' + encodedmsg + ' + ' </br> ');            };            Sets the focus format for the message box.            $ (' #message '). focus (); Establish a connection with the server $.connection.hub.start (). Done (function () {$ (' #sendmessage '). Click Ction () {///Call the Send method Chat.server.send ($ (' #displayname ') in the hub. Val (), $ (' #message '                    ). Val ());                Empty the message input box $ (' #message '). Val ("). focus ();            });        });    }); </script></body>

5. Create the OWin Startup startup class in the project and add the following code to the configuration (Iappbuilder app): App.   Maphubs (); The meaning of this code is to map the application to the Hub, which is executed when the program starts running.

6. Add the ChatHub.cs class and create the Send (string name, String message) method so that the client can invoke the

    public class Chathub:hub    {public        void Send (string name, String message)        {            Clients.All.broadcastMessage (name, message);        }    }

7. Compile the project, if it is not wrong, the results of the program execution should be like this (the following is the fire Fox browser):

When debugging with IE, we can see some auto-generated call scripts in the project, where Hubs.js is a <script src= "signalr/hubs" > </script> that we refer to on the client. It will push the methods in the server to the client so that the client can invoke the

The complete code for Hubs.js is as follows:

/*! * ASP. SignalR JavaScript Library v2.1.2 * http://signalr.net/* Copyright Microsoft Open Technologies, Inc. All rights reserved. * Licensed under the Apache 2.0 * https://github.com/SignalR/SignalR/blob/master/LICENSE.md * *////<reference path= ". .\.. \signalr.client.js\scripts\jquery-1.6.4.js "/>///<reference path=" jquery.signalR.js "/> (function ($,    window, undefined) {//<param name= "$" type= "JQuery"/> "Use strict"; if (typeof ($.SIGNALR)!== "function") {throw new Error ("SIGNALR:SIGNALR is not loaded.    Ensure Jquery.signalr-x.js is referenced before ~/signalr/js. ");    var SignalR = $.signalr;            function Makeproxycallback (hub, callback) {return function () {//Call the client hub method        Callback.apply (Hub, $.makearray (arguments));    }; } function Registerhubproxies (instance, shouldsubscribe) {var key, hub, Memberkey, Membervalue, Subscriptionmet        Hod For (Key in InstaNCE) {if (Instance.hasownproperty (key)) {hub = Instance[key]; if (! (                Hub.hubname)) {//Not a client hub continue; } if (Shouldsubscribe) {//We want to subscribe to the hub events Su                Bscriptionmethod = Hub.on;                 } else {//We want to unsubscribe from the hub events Subscriptionmethod = Hub.off; }//Loop through all members on the hub and find client hub functions to SUBSCRIBE/UNSUBSC                        Ribe for (Memberkey in hub.client) {if (Hub.client.hasOwnProperty (Memberkey)) {                        Membervalue = Hub.client[memberkey]; if (!$.isfunction (Membervalue)) {//Not a client hub function conti                        Nue } subscriptIonmethod.call (Hub, Memberkey, Makeproxycallback (Hub, Membervalue)); }}}}} $.hubconnection.prototype.createhubproxies = function () {var pro        Xies = {};             This.starting (function () {//Register the hub proxies as subscribed//(instance, Shouldsubscribe)            Registerhubproxies (proxies, true);        This._registersubscribedhubs ();  }). Disconnected (function () {//unsubscribe all hub proxies when we "disconnect".            This was to ensure, that we don't re-add functional call backs.        (instance, shouldsubscribe) registerhubproxies (proxies, false);        });         proxies[' Chathub ' = This.createhubproxy (' Chathub ');        proxies[' Chathub '].client = {}; proxies[' Chathub '].server = {send:function (name, message) {return proxies[' Chathub '].invoke. Apply (proxies[' Chathub '), $.merge (["Send"], $.makearray (arguments)));        }        };    return proxies;    };    Signalr.hub = $.hubconnection ("/signalr", {usedefaultpath:false}); $.extend (SignalR, SignalR.hub.createHubProxies ());} (Window.jquery, window));

Well, thank you very much for reading, if you have any good ideas, welcome to communicate with me.

Source code: Download Source code

SignalR + MVC 4 Web application

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.