Monday, 13 February 2012

Insert Record using json an jquery

Html Page


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ChatWindow.aspx.cs" Inherits="ChatWindow" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" type="text/css" href="base.css" />
    <link rel="stylesheet" type="text/css" href="theme.css" />
    <script src="Script/jquery-1.7.1.js" type="text/javascript"></script>
    <script src="Script/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">

        $(document).ready(function (e) {
            $('#<%=TxtMsg.ClientID%>').keypress(function (e) {              
                if (e.keyCode == 13) {
                    var msg = $('#<%=TxtMsg.ClientID %>').val();
                    InsertChatMesage(msg);
                    $('#<%=TxtMsg.ClientID %>').val('');
                }
            });
            $('#header').click(function () {
                // $('#ChatDiv').slideToggle('slow');
                $('#ChatDiv').slideDown('slow');
                $('#ChatDiv').hide();
                // $('#ChatDiv').toggle('slow');
                $('#ChatFooter').show("slow");
            });

            $('#ChatFooter').click(function () {
                $('#ChatDiv').show("slow");
                $('#ChatFooter').hide("slow");
            });

//            $("#close").click(function () {

//                $('#output').css({ left: leftVal, top: topVal }).hide("slow");
//            }); //close div click

        });

        //=====================================================


        function InsertChatMesage(msg) {
            var sessionid = $('#Hdn_sessionid').val();
            var Recsessionid = $('#Hdn_RecSessionID').val();
            var senderid = $('#Hdn_senderid').val();
            var reciptantid = $('#Hdn_recid').val();
            var message = msg;
            var d = { SenderSessionid: sessionid, ReceiverSessionid: Recsessionid, senderid: senderid, Receipientid: reciptantid, message: message };
            var data1 = JSON.stringify(d);
            $.ajax({

                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "ChatWebservice.asmx/InsertChatMessage",
                data: data1,
                dataType: "json",
                success: insertCallback
            });
            function insertCallback(result) {
                var res = result.d;
                var table = '<table cellpadding=0 cellspacing=10>';

                if (res != null) {
                    for (var i = 0; i < res.length; i++) {
                        table += '<tr><td><img height=30px width=30px src=' + res[i].IImage + '></td><td>' + res[i].SenderName + ':</td><td>' + res[i].message + '</td></tr>';
                    }
                    table += '</table>';
                    $('#msgheader').html(table);
                    $('#header').html('Contacts', 'Image/minus.png');
                }
            }
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <asp:HiddenField ID="Hdn_senderid" runat="server" />
    <asp:HiddenField ID="Hdn_recid" runat="server" />
    <asp:HiddenField ID="Hdn_sessionid" runat="server" />
    <asp:HiddenField ID="Hdn_RecSessionID" runat="server" />
    <div id="ChatDiv" style="width:220px;border-width:1;border-style:outset" class="MsgContainer" >
        <div id="header" style="background-color:#A4A4A4;font-weight:bold;width:220px;height:25px">
        <img align="right" src="Image/minus.png" id="toggle" border="0" >
        <%-- <div id="closepopup">
                <div id="close" class="ClosePopup">
                </div>
          </div>--%>
        </div>  
        <div id="msgheader" style="width:220px;height:250px;border:2px ;overflow:auto ">
        </div>
        <div id="msgcontent">
        <asp:TextBox ID="TxtMsg" runat="server" TextMode="MultiLine" Height="52px"
                Rows="10" Width="97%" style="overflow:auto;"></asp:TextBox>
        </div>    
   </div>
   <div id="ChatFooter" style="background-color:blue;width:220px;height:25px;display:none;position:absolute" class="MsgContainer">      
   <img src="Image/plus.png" id="Img1" border="0" align="right" >  
   </div>
  </form>
</body>
</html>

Web Service


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Web.Configuration;
using System.Data.SqlClient;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class ChatWebservice : System.Web.Services.WebService
{
    string connString = WebConfigurationManager.ConnectionStrings["CONN"].ConnectionString.ToString();
    [WebMethod]
    public List<MessageList> InsertChatMessage(string SenderSessionid, string ReceiverSessionid, string senderid, string Receipientid, string message)
    {      
        SqlCommand cmd;
        string insquery = "";
        List<MessageList> msgdata = new List<MessageList>();
        SqlConnection con = new SqlConnection(connString);
        con.Open();
        for (int i = 0; i < 2; i++)
        {
            if (i == 0)
                insquery = "insert into Message(MessageListSessionId,SenderUserId,RecipientUserId,MessageContents,IsTyping,MessageTime) values('" + SenderSessionid + "','" + senderid + "','" + Receipientid + "','" + message + "','1','" + DateTime.Now + "')";
            if (i == 1)
                insquery = "insert into Message(MessageListSessionId,SenderUserId,RecipientUserId,MessageContents,IsTyping,MessageTime) values('" + ReceiverSessionid + "','" + senderid + "','" + Receipientid + "','" + message + "','1','" + DateTime.Now + "')";
            cmd = new SqlCommand(insquery, con);
            cmd.ExecuteNonQuery();
        }
        DataTable dtmessage = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter("select a.UserName,a.UImage,b.MessageContents from UserMaster a,Message b where a.Userid=b.SenderUserId and b.MessageListSessionId='" + SenderSessionid + "'", con);
        da.Fill(dtmessage);
        foreach (DataRow dr in dtmessage.Rows)
        {
            MessageList ml = new MessageList();
            ml.SenderName = dr["UserName"].ToString().Trim();
            ml.IImage = "Image/" + dr["UImage"].ToString().Trim();
            ml.message = dr["MessageContents"].ToString().Trim();
            msgdata.Add(ml);
        }
        con.Close();
        return msgdata.ToList();
    }

}
public class MessageList
{
    public string SenderName
    {
        get;
        set;
    }
    //public string ReceiverName
    //{
    //    get;
    //    set;
    //}
    public string IImage
    {
        get;
        set;
    }
    public string message
    {
        get;
        set;
    }

}







No comments:

Post a Comment