ChatHub.cs
namespace AmyChat.Hubs { public class ChatHub : Hub { UserDAL userDAL = new UserDAL(); public void Hello(string str,string val) { var userId = Context.User.Identity.GetUserId(); var userList = userDAL.GetFriendList(userId); var ids = from u in userList select u.Id; Clients.Users(ids.ToList()); Clients.All.takeYou(str); } } }
UserDAL.cs
public class UserDAL { private ApplicationDbContext _db = new ApplicationDbContext(); public IEnumerable<ApplicationUser> GetFriendList(string userId) { IEnumerable<ApplicationUser> friendList = from u in _db.Users join fr in _db.Friends on u.Id equals fr.BId where fr.AId == userId select u; return friendList; } }
Index.cshtml
@{ ViewBag.Title = "Index"; var select1 = (SelectList)ViewData["select1"]; } @section Scripts{ <script src="~/Scripts/jquery-3.1.1.js"></script> <script src="~/Scripts/jquery.signalR-2.2.1.js"></script> <script src="/signalr/hubs"></script> <script> $(function () { var chat = $.connection.chatHub; $.connection.hub.start(); //console.log(chat.client); chat.client.takeYou = function (str) { //console.log(str); $("#divMsg").append(str); }; $("#btnSend").click(function () { var content = $("#content").val(); chat.server.hello(content, $(friendId).val()); }); }); </script> } <label for="friendId">好友</label> @Html.DropDownList("friendId", select1, new { id="friendId"}) <input type="text" name="content" id="content" value="" /> <button type="button" id="btnSend">发送</button> <div id="divMsg"></div>
ChatController
[Authorize] public class ChatController : Controller { ApplicationDbContext _db = new ApplicationDbContext(); UserDAL userDAL = new UserDAL(); // GET: Chat public ActionResult Index() { var friendList = userDAL.GetFriendList(User.Identity.GetUserId()); SelectList select1 = new SelectList(friendList, "Id", "UserName"); ViewData["select1"] = select1; return View(); } }