Click here to Skip to main content
12,954,856 members (75,912 online)
Rate this:
 
Please Sign up or sign in to vote.
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 23-Nov-11 19:27pm
Updated 24-Nov-11 18:37pm
v5
Comments
Sunasara Imdadhusen 24-Nov-11 5:45am
   
Have you written any code for that?
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

// 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.

 
 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.
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

i finally find the solution for this..and it works efficiently.. :)
 
//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>
  Permalink  
v6

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

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 6,539
CHill60 3,490
Maciej Los 3,153
ppolymorphe 2,030
Jochen Arndt 1,975


Advertise | Privacy | Mobile
Web02 | 2.8.170525.1 | Last Updated 19 Feb 2014
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100