Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
3.00/5 (3 votes)
Hello,
I need to insert form data into sql database using AJAX with JSON and show in gridview.
Can anybody help me?
Thanks in advance.
Posted
Updated 24-Nov-11 18:37pm
v5
Comments
Sunasara Imdadhusen 24-Nov-11 5:45am    
Have you written any code for that?

// You can use below link to insert data through AJAX- JSON

CLICK HERE[^]

//To show data you can use following code which gets data from webservice through JSON and rendor it in HTML table and apply CSS to it.

JavaScript
 var CompanyId = document.getElementById("CompanyId").value;
    var UserId = document.getElementById("_UserId").value;
    var RoleId = $("#RoleId").val();
    
   
    $.ajax({
        type: "POST",
        url: "../../WebService/CustomerOrder.asmx/GetOrderTrackingData",
        data: "{CompanyId:" + CompanyId + ",UserId:" + UserId + ",WhereCondition:'" + WhereCondition + "',RoleId:'" + RoleId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            var OrdTrackingData = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
            for (var i = 0; i < OrdTrackingData.length; i++) {
                $("#tbody").append("<tr><td id="tdOrderid" style="display:none">" + OrdTrackingData[i].OrderId + "</td>" +
                                        "<td class="Normal">" + OrdTrackingData[i].PWSID +
                                        "</td><td class="Normal">" + OrdTrackingData[i].OrderNo + "</td>" +
                                        "<td class="Normal">" + OrdTrackingData[i].Status + "</td>" +
                                        "<td class="Normal">" + OrdTrackingData[i].Name + "</td>" +
                                        "<td class="Normal">" + OrdTrackingData[i].Price + "</td>" +
                                        "<td class="Normal">" + OrdTrackingData[i].Service + "</td>" +
                                        "<td class="Normal">" + OrdTrackingData[i].OrderDate + "</td>"
                                        );

            }
            SetCssRule();
            
    );
        },
        error: OnError
    });
</tr>


Mark as solution if its solved your problem.
 
Share this answer
 
i finally find the solution for this..and it works efficiently.. :)
C#
//in .aspx page
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
    Inherits="_Default" %>


<html>
<head>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function getData(userid) {
            var params = "{userid:'" + userid + "'}";
            //debugger;
            //alert("inside" + userid);
            $.ajax
                ({
                    type: "POST",
                    data: params,
                    url: "Default.aspx/getdata",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        //alert('success');
                        var objJson = result.d;
                        $("#<%=txtDivUname.ClientID %>").val(objJson.username);
                        $("#<%=txtDivCno.ClientID %>").val(objJson.contactno);
                        document.getElementById("hdnID").value = objJson.userid;
                    },
                    error: function () {
                        alert("fail");
                    }
                });
            $('#divDialog').dialog('open');
            return false;
        };

        $(document).ready(function () {
            $('#divDialog').dialog({
                autoOpen: false,
                modal: true,
                resizable: true,
                //title: 'Edit Data',
                width: 310,
                height: 210,
                hide: 'explode',
                closeOnEscape: false,
                open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); }
            });
            $("#divDialog").parent().appendTo("#parentdiv");

            $("#<%=btnNew.ClientID %>").click(function () {
                $('#divDialog').dialog('open');
                return false;
            });

            $("#<%=btnDivAdd.ClientID %>").click(function () {
                //debugger;
                var username = $("#<%=txtDivUname.ClientID %>").val();
                var contactno = $("#<%=txtDivCno.ClientID %>").val();
                var params = "{username:'" + username + "',contactno:'" + contactno + "'}";
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/addDetail",
                    data: params,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        var objJson = result.d;
                        if (objJson == 1) {
                            alert("Record added successfully..")
                        }
                        else if (objJson == 2) {
                            alert("Error in adding record");
                        }
                    },
                    error: function () {
                        alert("Error in adding record");
                    }
                });
                //return true;
            });

            $("#<%=btnDivUpdate.ClientID %>").click(function () {
                //debugger;
                var uname = $("#<%=txtDivUname.ClientID %>").val();
                var cno = $("#<%=txtDivCno.ClientID %>").val();
                var uid = document.getElementById("hdnID").value;
                document.getElementById("hdnEditFlag").value = true;
                var params = "{username:'" + uname + "',contactno:'" + cno + "',userid:'" + uid + "'}";
                $.ajax({
                    type: "POST",
                    data: params,
                    url: "Default.aspx/updatedata",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        alert("Record updated successfully..");
                    },
                    error: function () {
                        alert("fail in updating record");
                    }
                });
                //return true;
            });

            $("#<%=btnDivClose.ClientID %>").click(function () {
                if (document.getElementById("hdnEditFlag").value == true && document.getElementById("hdnDeleteFlag").value == true) {
                    $('#divDialog').dialog('close');
                    return true;
                }
                else
                    $('#divDialog').dialog('close');
                return false;
            });

            $("#<%=btnDivDelete.ClientID %>").click(function () {
                //alert("in delete");
                //debugger;
                var uid = document.getElementById("hdnID").value;
                document.getElementById("hdnDeleteFlag").value = true;
                var params = "{userid:'" + uid + "'}";
                $.ajax({
                    type: "POST",
                    data: params,
                    url: "Default.aspx/deletedata",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) {
                        alert("Record deleted successfully..");
                    },
                    error: function () {
                        alert("fail in delete record");
                    }
                });
                return true;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Button ID="btnContext" Text="context" runat="server"
        onclick="btnContext_Click" />
    <asp:Label ID="lblContext" runat="server" Text=""></asp:Label>

    <asp:Button ID="btnNew" runat="server" Text="New.." /><br />
    <br />
    <div id="parentdiv">
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand"
        OnRowDataBound="GridView1_RowDataBound" DataKeyNames="userid">
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:Label runat="server" Text="User Name" />
                    <asp:Label runat="server" Text="Contant No" />
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:LinkButton ID="lnkbtnUname" runat="server" Text='<%#Eval("username") %>' CommandName="udata"
                        CommandArgument='<%#Eval("userid") %>' />
                    <asp:Label runat="server" Text='<%#Eval("contactno") %>' />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <br />
    <div id="divDialog">
        <div style="background-color: ButtonShadow">
            <asp:Label ID="lblDialogHeader" runat="server" Text="User Data ::"></asp:Label>
        </div>
        <div style="background-color: white">
            <table id="tblUser" runat="server">
                <tr>
                    <td>
                        <asp:Label ID="lblDivUname" runat="server" Text="User Name ::"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="txtDivUname" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="lblDivCno" runat="server" Text="Contact No ::"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="txtDivCno" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="btnDivUpdate" runat="server" Text="Update.." />
                    </td>
                    <td>
                        <asp:HiddenField ID="hdnID" runat="server" Value="" />
                        <asp:HiddenField ID="hdnEditFlag" runat="server" Value="false" />
                        <asp:Button ID="btnDivClose" runat="server" Text="Close.." />
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:HiddenField ID="hdnDeleteFlag" runat="server" Value="false" />
                        <asp:Button ID="btnDivDelete" runat="server" Text="Delete.." />
                    </td>
                    <td>
                        <asp:Button ID="btnDivAdd" runat="server" Text="Add.." />
                    </td>
                </tr>
            </table>
        </div>
    </div>
    </form>
</body>
</html>



//in aspx.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data;

public class entity
{
    public string username { get; set; }
    public int? contactno { get; set; }
    public int userid { get; set; }
    public entity()
    {

    }
}

public class entityJson
{
    public string username { get; set; }
    public string contactno { get; set; }
    public string userid { get; set; }
    public entityJson()
    {
        username = ""; contactno = ""; userid = "";
    }
}
public partial class _Default : System.Web.UI.Page
{      
    int userid;
    protected void Page_Load(object sender, EventArgs e)
    {
        //ScriptManager.RegisterClientScriptInclude(this.Page, this.GetType(), "jquery", ResolveUrl("js/jquery-1.3.2.js"));
        //if (!IsPostBack)
        bind();
        //entity ojbent = new entity();
        //ojbent.username = "asd";
        //ojbent.contactno = 123;
        //HttpContext.Current.Items.Add("asd", "123");
        //Server.Transfer("About.aspx");
    }
    [WebMethod(EnableSession = true)]
    public static int addDetail(string username, int contactno)
    {
        try
        {
            DataClassesDataContext db = new DataClassesDataContext();
            utable usertable = new utable();
            usertable.username = username;
            usertable.contactno = contactno;
            db.utables.InsertOnSubmit(usertable);
            db.SubmitChanges();            
            return 1;
        }
        catch
        {
            return 2;
        }
    }
    public void bind()
    {
        DataClassesDataContext db = new DataClassesDataContext();
        IList<entity> lstData = (from ut in db.utables
                                 select new entity
                                {
                                    userid = ut.userid,
                                    username = ut.username,
                                    contactno = ut.contactno
                                }).ToList();
        GridView1.DataSource = lstData;
        GridView1.DataBind();
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "udata")
        {
            userid = int.Parse(e.CommandArgument.ToString());
            //ViewState["uid"] = userid;
        }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        entity obj = (entity)e.Row.DataItem;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //int userid = int.Parse(ViewState["uid"].ToString());            
            ((LinkButton)e.Row.FindControl("lnkbtnUname")).Attributes.Add("onClick", "javascript: getData('" + obj.userid + "'); return false;");
        }
    }
    [WebMethod(EnableSession = true)]
    public static entityJson getdata(int userid)
    {
        DataClassesDataContext db = new DataClassesDataContext();
        //return (from ut in db.utables
        //        where ut.userid == userid
        //        select new entity
        //        {                    
        //            username = ut.username,
        //            contactno = ut.contactno
        //        }).FirstOrDefault();
        entityJson obje = (from ut in db.utables
                           where ut.userid == userid
                           select new entityJson
                           {
                               username = ut.username,
                               contactno = ut.contactno.HasValue ? ut.contactno.ToString() : "",
                               userid = ut.userid.ToString()
                           }).FirstOrDefault();
        return obje;
    }
    [WebMethod(EnableSession = true)]
    public static void updatedata(string username, string contactno, string userid)
    {
        DataClassesDataContext db = new DataClassesDataContext();
        db.Connection.Open();
        utable utab = db.utables.Single(ut => ut.userid == int.Parse(userid));
        utab.username = username;
        utab.contactno = int.Parse(contactno);
        db.SubmitChanges();        
    }
    [WebMethod(EnableSession = true)]
    public static void deletedata(string userid)
    {
        DataClassesDataContext db = new DataClassesDataContext();
        db.Connection.Open();
        utable utab = db.utables.Single(ut => ut.userid == int.Parse(userid));
        var delquery = from udata in db.utables where udata.userid == int.Parse(userid) select udata;
        db.utables.DeleteOnSubmit(utab);
        db.SubmitChanges();
        db.Connection.Close();
    }    
}



//you need to add jquery-1.4.1.js,jquery-1.4.1.min.js,jquery-1.4.1-vsdoc.js
</entity>
 
Share this answer
 
v6

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900