ASP.NET ve JSON İle Veri Çekme, Json’dan daha önce başka bir makalede bahsetmiştik şimdi ajax ve json’i kullanarak aspx sayfası ile öğrenci notlarını sayfaya yazdırmayı göreceğiz. Veritabanı işlemleri için Entity Framework kullanıyoruz.
ASP.NET Ve JSON İle Veri Çekme
ogrenci.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 | <div> <span>Öğrenci Notları</span> <table border="1" id="ogrenciBilgi"> <thead> <tr> <th>No</th> <th>Adı</th> <th>Notu</th> </tr> </thead> </table> <asp:hiddenfield id="ogrenciBilgileri" runat="server"> </asp:hiddenfield> </div> |
personel.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | using System; using System.Linq; using System.Web.Script.Serialization; namespace ajax_veri_cekme { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { OGRENCIEntities ogr = new OGRENCIEntities(); JavaScriptSerializer js = new JavaScriptSerializer(); ogrenciBilgileri.Value = js.Serialize(ogr.OGRENCI_NOT.ToList()); } } } |
Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $(function ogrenciGetir() { try { var obj = null; obj = JSON.parse($("#ogrenciBilgileri").val()); var body = document.createElement("tbody"); for (var i = 0; i < obj.length; i++) { var tr = document.createElement("tr"); var tdID = document.createElement("td"); var tdAd = document.createElement("td"); var tdNot = document.createElement("td"); tdID.textContent = obj[i].OGRID; tdAd.textContent = obj[i].OGRADI; tdNot.textContent = obj[i].OGRNOT; tr.appendChild(tdID); tr.appendChild(tdAd); tr.appendChild(tdNot); body.appendChild(tr); } $("#ogrenciBilgi").append(body); } catch(e) { alert("Hata: " + e); } }) |
Kısaca özetlersek veritabanındaki verileri sayfa yüklendiğinde yani load event(olay)’inde hiddenfield nesnesine aktarıyoruz ve javascript ile verileri hiddenfield nesnesinden alıp sayfaya yazdırıyoruz.