1.在引用中添加signalr后首选要引入Startup.cs类,在VS2012中添加Signalr后没有Startup.cs类然后就会报错 代码如下
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Owin; using Microsoft.Owin; [assembly: OwinStartup(typeof(CarportManage.Startup))] namespace CarportManage { public class Startup { public void Configuration(IAppBuilder app) { // Any connection or hub wire up and configuration should go here app.MapSignalR(); } } }
2写一个发送类
1 using Microsoft.AspNet.SignalR; 2 using System; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Web; 6 7 namespace CarportManage.Models 8 { 9 public class seedmessage:Hub 10 { 11 public void Send(object message) 12 { 13 IHubContext chat = GlobalHost.ConnectionManager.GetHubContext<seedmessage>(); 14 chat.Clients.All.add(message); 15 16 } 17 } 18 }
3后台代码调用发送类
using CarportManage.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CarportManage.Controllers { public class AlertController : Controller { // // GET: /Alert/ CardManageEntities3 db = new CardManageEntities3(); public ActionResult Index() { return View(); } public ActionResult show() { return View(); } public ActionResult insert(FormCollection from) { int success; try { CardManage t = new CardManage(); t.userName = from["add_name"]; t.userTel = from["add_tel"]; t.carNum = from["add_carNum"]; t.userDep = from["add_dep"]; t.fixedCarport = from["add_fixedCarport"]; db.CardManage.Add(t); db.SaveChanges(); seedmessage s = new seedmessage(); s.Send(t); success = 1; } catch (Exception) { success = 0; } //new { success = true } return Content(success.ToString()); } } }
4前端代码块
Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <script src="~/Scripts/jquery-1.7.1.js"></script> <script src="~/Scripts/jquery.signalR-2.1.2.js"></script> <script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script> <script src="~/signalr/hubs"></script> <script type="text/javascript"> var pushHub = $.connection.seedmessage; pushHub.client.add= function (message) { alert(message.userName); alert(message.userTel); } $.connection.hub.start(); </script> <title>接收端</title> </head> <body> <div> </div> </body> </html>