2.3.5. Sending Messages To Different Groups

  • 1.Add a new action and view in controller:

    • action

      // GET: Chat/Welcome
        public ActionResult Welcome()
        {
            return View("Welcome");
        }
    • view

      @{
        ViewBag.Title = "Welcome";
      }
      
      <h2>Welcome to signalR chat App</h2>
      <form action = "/Chat/Index" method = "get">
      <table>
        <tr>
            <td>Select Room/Group</td>
            <td>
                <select name="g">
                    <option value="MVC">Select</option>
                    <option value="MVC">MVC</option>
                    <option value="SignalR">SignalR</option>
                    <option value="WCF">WCF</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>Enter your name:</td>
            <td><input type="text" name="n" />someone</td>
        </tr>
        <tr>
            <td><input type="submit" value="Start Chating" /></td>
        </tr>
      </table>
      </form>
  • 2.Modify hub:

      public void servermethod(string name, string msg, string group)
          {
              string ConId = Context.ConnectionId.ToString();
              // call the clients connected to the hub
              Clients.Group(group).clientmethod(name, ConId, msg);
          }
  • 3.Modify chat page:

                  //Get query string
                  function queryString(Key)
                  {
                      var url = window.location.href;
                      KeysValues = url.split(/[\?&]+/);
                      for(i = 0; i < KeysValues.length; i++)
                      {
                          KeysValue = KeysValues[i].split("=");
                          if (KeysValue[0] == Key)
                          {
                              return KeysValue[1];
                          }
                      }
                  }
    
                      $(document).ready(function () {
    
                      //Get name from query string
                      var n = queryString("n");
    
                      $("#name").html(n);
    
                      //Get group from query string
                      var g = queryString("g");

Last updated