SignalR和MVC 5部分视图

时间:2016-12-23 11:23:42

标签: asp.net-mvc signalr partial-views signalr.client

嘿伙计我有Asp SignalR的以下问题。我想与管理员和用户聊天。我有一个带有两个div的视图(对于Admin为!而对用户为1),我通过检查用户显示或隐藏它。到目前为止一切顺利,一切正常!管理员和用户都获得必要的div并可以交换消息 - red div admin, blue div user.。看看代码,我会解释我遇到问题的地方。

<div class="Admin" id="divMessageAdmin" style="background-color:red;">
    <div class="welcome"></div><br />
    <div id="divWaitingUser"></div><br />
    <input id="txtMessage" type="text" />
    <input id="btnSendMessage" type="button" value="Send" />
    <div id="divAdminMessage"></div>
</div>

<div class="User" id="divMessageUser" style="background-color:blue;">
    <div class="welcome"></div><br />
    <input id="txtUserMessage" type="text" />
    <input id="btnSendUserMessage" type="button" value="Send" />
    <div id="divUserMessage"></div>
</div>

    <input id="hUserId" type="hidden" />
    <input id="hId" type="hidden" />
    <input id="hUserName" type="hidden" />
    <input id="hGroup" type="hidden" />

@section scripts {
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
    <script src="~/signalr/hubs" type="text/javascript"></script>

    <script>
        $(function () {
           var objHub = $.connection.chatHub;
           loadClientMethods(objHub);
           $.connection.hub.start().done(function () {
               loadEvents(objHub);
           });
       });

       function loadEvents(objHub) {

           var name = '@HttpContext.Current.User.Identity.Name';
           objHub.server.connect(name);
           //alert(name);

           $('#btnSendMessage').click(function () {
               var msg = $("#txtMessage").val();
               if (msg.length > 0) {
                   var username = $('#hUserName').val();
                   document.getElementById('txtMessage').value = "";
                   // <<<<<-- ***** Return to Server [  SendMessageToGroup  ] *****
                   objHub.server.sendMessageToGroup(username, msg);
               }
           });

           $('#btnSendUserMessage').click(function () {
              // alert("wrks");
               var msg = $("#txtUserMessage").val();
               if (msg.length > 0) {
                   var username = $('#hUserName').val();
                   document.getElementById('txtUserMessage').value = "";
                   // <<<<<-- ***** Return to Server [  SendMessageToGroup  ] *****
                   objHub.server.sendMessageToGroup(username, msg);
               }
           });

           $("#txtMessage").keypress(function (e) {
               if (e.which == 13) {
                   $('#btnSendMessage').click();
               }
           });
       }

        function loadClientMethods(objHub) {

           objHub.client.getMessagesAdmin = function (userName, message) {
                   $(".txtMessage").val('');
                   $('#divAdminMessage').append('<div><p>' + userName + ': ' + message + '</p></div>');
                   var height = $('#divAdminMessage')[0].scrollHeight;
                   $('#divAdminMessage').scrollTop(height);
           }

           objHub.client.getMessagesUser = function (userName, message) {
               $("#txtMessage").val('');
               $('#divUserMessage').append('<div><p>' + userName + ': ' + message + '</p></div>');
               var height = $('#divUserMessage')[0].scrollHeight;
               $('#divUserMessage').scrollTop(height);
           }

           objHub.client.onConnected = function (id, userName, UserID, userGroup, flag) {
               alert(flag);
               var strWelcome = 'Welcome' + +userName;
               $('.welcome').append('<div><p>Welcome:' + userName + '</p></div>');
               $('#hId').val(id);
               $('#hUserId').val(UserID);
               $('#hUserName').val(userName);
               $('#hGroup').val(userGroup);
               if ( flag == "1") {
                   $("#divMessageUser").hide();
                   $("#divMessageAdmin").show();
               }
               else {
                   $("#divMessageUser").show();
                   $("#divMessageAdmin").hide();
               }
           }
       }
    </script>
}

问题是,我希望这两个div在分开的部分视图中。这就是我正在尝试的。在我的页面的开头,我检查用户是否经过身份验证,如果是我在我的ChatController中触发[ChildActionOnly]操作方法:

<h2>Chat</h2>
@{
    if (!User.Identity.IsAuthenticated)
    {
        @Html.Partial("_UnauthenticatedUserForm");
    }
    else
    {
        Html.RenderAction("AuthenticatedUsersChat");
    }
}

和我在控制器中的动作方法

[ChildActionOnly]
public ActionResult AuthenticatedUsersChat()
{
    AppContext db = new AppContext();
    User user = db.Users.Single(usr => usr.Email == User.Identity.Name);
    int isAdmin = user.AdminCode;
    if (isAdmin == 0)
    {
        return PartialView("_UserChatPartial");
    }
    else
    {
        return PartialView("_AdminChatPartial");
    }
}

这是有效的,部分视图以我想要的方式返回。在两个局部视图中,我只移动了div!管理员部分:

<div class="Admin" id="divMessageAdmin" style="background-color:red;">
    <div class="welcome"></div><br />
    <div id="divWaitingUser"></div><br />
    <input id="txtMessage" type="text" />
    <input id="btnSendMessage" type="button" value="Send" />
    <div id="divAdminMessage"></div>
</div>

和UserPartial

<div class="User" id="divMessageUser" style="background-color:blue;">
    <div class="welcome"></div><br />
    <input id="txtUserMessage" type="text" />
    <input id="btnSendUserMessage" type="button" value="Send" />
    <div id="divUserMessage"></div>
</div>

但不知何故只有管理员才能看到这些消息。用户可以发送消息(管理员收到消息),但用户无法看到他或管理员的消息 - result。我根本没有看到任何逻辑,为什么只有用户看不到消息。如果您有任何想法,请帮助我。提前致谢 !

我在集线器类中的消息方法

public void SendMessageToGroup(string userName, string message)
{
    if (UsersList.Count != 0)
    {
        var strg = (from s in UsersList where (s.Email == userName) select s).First();
        MessageList.Add(new MessageInfo { UserName = userName, Message = message, UserGroup = strg.UserGroup });
        string strgroup = strg.UserGroup;
        Clients.Group(strgroup).getMessagesAdmin(userName, message);
        Clients.Group(strgroup).getMessagesUser(userName, message);
    }
}
// End SendMessage

和集线器中的连接方法

public void Connect(string userName)
{
        //if freeflag==0 ==> Busy
        //if freeflag==1 ==> Free

        //if tpflag==0 ==> User
        //if tpflag==1 ==> Admin

    var id = Context.ConnectionId;
    string userGroup = "";

    AppContext db = new AppContext();
    var userInfo = (from m in db.Users
                    where m.Email == HttpContext.Current.User.Identity.Name
                    select new { m.UserId, m.Email, m.AdminCode, m.FirstName, m.LastName }).FirstOrDefault();

    try
    {
        if ((int)userInfo.AdminCode == 0)
        {
            var strg = (from s in UsersList where (s.tpflag == "1") && (s.freeflag == "1") select s).First();
            userGroup = strg.UserGroup;
            strg.freeflag = "0";
            //now add USER to UsersList
            UsersList.Add(new User { ConnectionId = id, UserId = userInfo.UserId, Email = userName, UserGroup = userGroup, freeflag = "0", tpflag = "0", });
            var flag = (from s in UsersList where (s.Email == userName) select s.tpflag); 
            Groups.Add(Context.ConnectionId, userGroup);
            Clients.Caller.onConnected(id, userName, userInfo.UserId, userGroup, flag);
        }
        else
        {
            UsersList.Add(new User { ConnectionId = id, UserId = userInfo.UserId, Email = userName, UserGroup = userInfo.AdminCode.ToString(), freeflag = "1", tpflag = "1" });
            var flag = (from s in UsersList where (s.Email == userName) select s.tpflag); 
            Groups.Add(Context.ConnectionId, userInfo.AdminCode.ToString());
            Clients.Caller.onConnected(id, userName, userInfo.UserId, userInfo.AdminCode.ToString(), flag);
        }
    }
    catch
    {
        Clients.Caller.NoExistAdmin();
    }
}

1 个答案:

答案 0 :(得分:1)

听起来您的“蓝色”用户不在您尝试发送的群组strgroup中。在SendMessageToGroup方法中为此行设置断点并进行检查。

同样奇怪的代码if ((int)userInfo.AdminCode == 0)为什么从First获取UsersList然后又添加到xsl:evaluate?这可能是例外吗?