title: ASP.NET MVC ajax chat
body: <p>I built an ajax chat in one of my mvc website. everything is working fine. I am using polling. At certain interval i am using $.post to get the messages from the db. But there is a problem. The message retrieved using $.post keeps on repeating. here is my javascript code and controller method.</p>
  
  <pre><code> var t;        
          function GetMessages() {        
              var LastMsgRec = $("#hdnLastMsgRec").val();
              var RoomId = $("#hdnRoomId").val();
              //Get all the messages associated with this roomId
              $.post("/Chat/GetMessages", { roomId: RoomId, lastRecMsg: LastMsgRec }, function(Data) {
                  if (Data.Messages.length != 0) {
                      $("#messagesCont").append(Data.Messages);
                      if (Data.newUser.length != 0)
                          $("#usersUl").append(Data.newUser);
                      $("#messagesCont").attr({ scrollTop: $("#messagesCont").attr("scrollHeight") - $('#messagesCont').height() });
                      $("#userListCont").attr({ scrollTop: $("#userListCont").attr("scrollHeight") - $('#userListCont').height() });
                  }
                  else {
                  }
                  $("#hdnLastMsgRec").val(Data.LastMsgRec);
              }, "json");
  
  
              t = setTimeout("GetMessages()", 3000);
          }
  </code></pre>
  
  <p>and here is my controller method to get the data:</p>
  
  <pre><code>public JsonResult GetMessages(int roomId,DateTime lastRecMsg)
          {
              StringBuilder messagesSb = new StringBuilder();
              StringBuilder newUserSb = new StringBuilder();            
              List&lt;Message&gt; msgs = (dc.Messages).Where(m =&gt; m.RoomID == roomId &amp;&amp; m.TimeStamp &gt; lastRecMsg).ToList();
              if (msgs.Count == 0)
              {
                  return Json(new { Messages = "", LastMsgRec = System.DateTime.Now.ToString() });
              }            
              foreach (Message item in msgs)
              {
                  messagesSb.Append(string.Format(messageTemplate,item.User.Username,item.Text));
                  if (item.Text == "Just logged in!")
                      newUserSb.Append(string.Format(newUserTemplate,item.User.Username));
              }            
  
              return Json(new {Messages = messagesSb.ToString(),LastMsgRec = System.DateTime.Now.ToString(),newUser = newUserSb.ToString().Length == 0 ?"":newUserSb.ToString()});
          }
  </code></pre>
  
  <p>Everything is working absloutely perfect. But i some messages getting repeated. The first time page loads i am retrieving the data and call GetMessages() function. I am loading the value of field <strong>hdnLastMsgRec</strong> the first time page loads and after the value for this field are set by the javascript.</p>
  
  <p>I think the message keeps on repeating because of asynchronous calls. I don't know, may be you guys can help me solve this.</p>
  
  <p><strong>or you can suggest better way to implement this.</strong></p>