Reuse ASPX page to generate JSON representation object
My Criteria:
a. reuse aspx page for a javascript to call one of my method in aspx.cs
b. return as JSON representation string
Here goes my code:
ASPX:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Test" %>
//include this in your header
<script src="jquery.min.js" type="text/javascript" />
<div id="test"%> </div%>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "Test1.aspx/GetJson",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#test").html(eval ( data.d ) );
//if server return as string, we need to use Eval to convert to object
}
})
});
</script>
Code Behind: ASPX.CS
//Make sure to include System.Web.Services in the project
using System;
using System.Web.Services;
namespace Test1
{
public partial class test
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetJson() {
var returnString = new {Country="Singapore", Sales=200};
return returnString;
}
}
}
a. reuse aspx page for a javascript to call one of my method in aspx.cs
b. return as JSON representation string
Here goes my code:
ASPX:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Test" %>
//include this in your header
<script src="jquery.min.js" type="text/javascript" />
<div id="test"%> </div%>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "Test1.aspx/GetJson",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#test").html(eval ( data.d ) );
//if server return as string, we need to use Eval to convert to object
}
})
});
</script>
Code Behind: ASPX.CS
//Make sure to include System.Web.Services in the project
using System;
using System.Web.Services;
namespace Test1
{
public partial class test
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetJson() {
var returnString = new {Country="Singapore", Sales=200};
return returnString;
}
}
}
Hope this help those who encounter my scenario.
Comments