Here's an example: c# asp.net
Jquery Examples
How it works:
Get List
Add this:
Json.NET
How to add...
Add Newton json
.js
function GetList() {
$.ajax({
async: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ExampleList.aspx/GetList",
dataType: "json",
success: function (data, textStatus) {
if (textStatus == "success") {
var datos = jQuery.parseJSON(data.d);
$("#List").html('');
var list = '<ul>'
$.each(datos, function (i, v) {
list += '<li id="'+v.id+'">' + v.value + '</li>'
});
list += '</ul>'
$("#List").append(list);
}
},
error: function (request, status, error) {
alert(jQuery.parseJSON(request.responseText).Message);
}
});
}
HTML|ASP
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExampleList.aspx.cs" Inherits="JqueryExamples.ExampleList" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input type="button" value="Get List" onclick="GetList()"/>
<div id="List">
</div>
</form>
<script src="Scripts/jquery.js"></script>
<script src="Scripts/ExampleListsa.js"></script>
</body>
</html>
Code Behind:
[WebMethod]
public static string GetList()
{
List<data> data = new List<data>();
try
{
data.Add(new Data { id = 1, value = "Alpha" });
data.Add(new Data { id = 2, value = "Beta" });
data.Add(new Data { id = 3, value = "Gamma" });
data.Add(new Data { id = 4, value = "Delta" });
data.Add(new Data { id = 5, value = "Epsilon" });
data.Add(new Data { id = 6, value = "Zeta" });
var rnd = new Random();
data = data.OrderBy(item => rnd.Next()).ToList();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
return JsonConvert.SerializeObject(data);
}
public partial class Data {
public int id { get; set; }
public string value { get; set; }
}
</data></data>
Can add a Class with a method to get the data from SQL, here's and example how to connect to SQL:
How to Connect SQL Database
In the Code Behind change the GetList Method for this:
public static string GetList()
{
List<data> data = new List<data>();
try
{
data = SqlClass.GetList();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
return JsonConvert.SerializeObject(data);
}