ذخیره کردن داده در پایگاه داده با استفاده از json و jquery در asp.net
دوشنبه 29 دی 1393در این مقاله میخواهیم که در asp.net اطلاعاتی را از کاربر بگیریم و با استفاده از json و jquery این اطلاعات را درون جدول خود ذخیره کنیم
ابتدا یک جدول به صورت زیر میسازیم:
حالا صفحه Defualt.aspx خودر را به شکل زیر تغییر دهید:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <style type="text/css"> <style type="text/css"> body { font-family: Verdana; font-size: 11px; } .errMsg { width: 200px; text-align: left; color: yellow; font: 12px arial; background: red; padding: 5px; display: none; } .tblResult { border-collapse: collapse; } .tblResult td { padding: 5px; border: 1px solid red; } .tblResult th { padding: 5px; border: 1px solid red; } img { cursor: pointer; } </style> </style> </head> <body> <form id="form1" runat="server"> <div> <table cellspacing="0" cellpadding="0"> <tr> <td colspan="2"> <%--//=== Here we will show error and confirmation messages.--%> <div class="errMsg"> </div> </td> </tr> <tr> <td> <b>Name</b> </td> <td> <asp:TextBox runat="server" ID="txtName" /> </td> </tr> <tr> <td> <b>Email</b> </td> <td> <asp:TextBox runat="server" ID="txtEmail" /> </td> </tr> <tr> <td> <b>Age</b> </td> <td> <asp:TextBox runat="server" ID="txtAge" /> </td> </tr> <tr> <td colspan="2"> <input type="button" onclick="saveData()" id="btnSave" value="Save" title="Save" /> </td> </tr> <tr> <td colspan="2"> <%--//==== We will show our data in this div--%> <div id="divData"> </div> </td> </tr> </table> </div> <script type="text/javascript"> function clear() { $("#txtName").val(""); $("#txtEmail").val(""); $("#txtAge").val(""); } function bindData() { $.ajax({ type: "POST", url: "Default.aspx/getData", data: "{}", contentType: "application/json; charset=utf-8", datatype: "jsondata", async: "true", success: function (response) { if ($('#tblResult').length != 0) // remove table if it exists { $("#tblResult").remove(); } var table = "<table class='tblResult' id=tblResult><thead> <tr><th>Name</th><th>Email</th><th>Age</th></thead> <tbody>"; for (var i = 0; i <= response.d.length - 1; i++) { var row = "<tr>"; row += '<td>' + response.d[i].Name + '</td>'; row += '<td>' + response.d[i].Email + '</td>'; row += '<td>' + response.d[i].Age + '</td>'; row += '</tr>'; table += row; } table += '</tbody></table>'; $('#divData').html(table); $("#divData").slideDown("slow"); }, error: function (response) { alert(response.status + ' chandan ' + response.statusText); } }); } function saveData() { var txtName = $("#txtName").val(); var txtEmail = $("#txtEmail").val(); var txtAge = $("#txtAge").val(); $.ajax({ type: "POST", url: "Default.aspx/saveData", data: "{name:'" + txtName + "',email:'" + txtEmail + "',age:'" + txtAge + "'}", contentType: "application/json; charset=utf-8", datatype: "jsondata", async: "true", success: function (response) { $(".errMsg ul").remove(); var myObject = eval('(' + response.d + ')'); if (myObject > 0) { bindData(); $(".errMsg").append("<ul><li>Data saved successfully</li></ul>"); } else { $(".errMsg").append("<ul><li>Opppps something went wrong.</li></ul>"); } $(".errMsg").show("slow"); clear(); }, error: function (response) { alert(response.status + ' ' + response.statusText); } }); } </script> </form> </body> </html>
خروجی به شکل زیر نمایش داده خواهد شد:
و در صفحه Defualt.aspx.cs کد های زیر را بنویسید:
[WebMethod] public static int saveData(string name, string email, string age) { try { int status = 1; string Query = string.Empty; SqlConnection cn = new SqlConnection("Data Source=sqlexpress; Initial Catalog=Json;Integrated Security=True"); Query = "INSERT INTO Student (Name,Email,Age,CreatedOn) VALUES ('" + name + "','" + email + "'," + age + ",GETDATE())"; SqlCommand cmd = new SqlCommand(Query, cn); cn.Open(); cmd.ExecuteNonQuery(); cn.Close(); return status; } catch { return -1; } } [WebMethod] public static Student[] getData() { string data = string.Empty; data = "dhdhdhddh"; StudentCollection sc = new StudentCollection(); try { SqlConnection con = new SqlConnection("Data Source=sqlexpress; Initial Catalog=Json;Integrated Security=True"); if (con.State == ConnectionState.Closed) { con.Open(); } SqlDataReader dr; SqlCommand cmd; string FetchData = "Select * From Student"; cmd = new SqlCommand(FetchData, con); dr = cmd.ExecuteReader(); if (dr.Read()) { while (dr.Read()) { Student s = new Student(); s.Name = dr[0].ToString(); s.Email = dr[1].ToString(); s.Age = dr[2].ToString(); sc.Add(s); } } return sc.ToArray(); } catch { return sc.ToArray(); } } } public class Student { public string Name { get; set; } public string Email { get; set; } public string Age { get; set; } } public class StudentCollection : List<Student> { public void Add(Student st) { base.Add(st); } }
پس از انجام مراحل بالا میتونید برنامه را اجرا کنید و خروجی به شکل زیر خواهد بود:
- ASP.net
- 3k بازدید
- 4 تشکر