1. 新增一個MVC4的專案
2. 選「網際網路應用程式」
3. 在「套件管理主控台」,安裝SingalR
4. 輸入 install-package Microsoft.AspNet.SignalR
5. 之後檢查script底下,應該有SignalR的相關Script
6. 接下來新增一個Hubs的資料夾
7. 新增一個 SignalR Hub Class
8.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | using System; using System.Web; using Microsoft.AspNet.SignalR; namespace SignalRChat { public class ChatHub : Hub { public void Send(string name, string message) { // Call the addNewMessageToPage method to update clients. Clients.All.addNewMessageToPage(name, message); } } } |
RouteTable.Routes.MapHubs();
10. 在「 Controllers/HomeController.cs」中新增一個 Chat 的 method
1 2 3 4 | public ActionResult Chat() { return View(); } |
11. 在View >> Home 底下新增一個 Chat 的 View
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | @{ ViewBag.Title = "Chat"; } <h2>Chat</h2> <div class="container"> <input type="text" id="message" /> <input type="button" id="sendmessage" value="Send" /> <input type="hidden" id="displayname" /> <ul id="discussion"> </ul> </div> @section scripts { <!--Script references. --> <!--The jQuery library is required and is referenced by default in _Layout.cshtml. --> <!--Reference the SignalR library. --> <script src="~/Scripts/jquery.signalR-1.0.1.js"></script> <!--Reference the autogenerated SignalR hub script. --> <script src="~/signalr/hubs"></script> <!--SignalR script to update the chat page and send messages.--> <script> $(function () { // Reference the auto-generated proxy for the hub. var chat = $.connection.chatHub; // Create a function that the hub can call back to display messages. chat.client.addNewMessageToPage = function (name, message) { // Add the message to the page. $('#discussion').append('<li><strong>' + htmlEncode(name) + '</strong>: ' + htmlEncode(message) + '</li>'); }; // Get the user name and store it to prepend to messages. $('#displayname').val(prompt('Enter your name:', '')); // Set initial focus to message input box. $('#message').focus(); // Start the connection. $.connection.hub.start().done(function () { $('#sendmessage').click(function () { // Call the Send method on the hub. chat.server.send($('#displayname').val(), $('#message').val()); // Clear text box and reset focus for next comment. $('#message').val('').focus(); }); }); }); // This optional function html-encodes messages for display in the page. function htmlEncode(value) { var encodedValue = $('<div />').text(value).html(); return encodedValue; } </script> } |
13.Google了好久,終於解決了
14. 在 BundleConfig.cs 中,加入 SignalR.js的 script, 另外因為IE解析 json 格式的問題,也要多加入 json2.js
1 2 3 | bundles.Add(new ScriptBundle("~/bundles/signalr").Include( "~/Scripts/json2.js", "~/Scripts/jquery.signalR-{version}.js")); |
可以在這邊取得: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
16. 另外在 View/Home/Chat.cshtml中,修改一下 SignalR.js include的方式
1 | @Scripts.Render("~/bundles/signalR") |
17. 在按 F5執行一次,http://localhost:xxxx/home/chat,終於成功了
沒有留言:
張貼留言