Thursday, October 22, 2009

Calling PageMethod using jQuery

a simple example:



html code:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function CallPageMethod()
{
var msg = '<%= this.Message %>';

$.ajax({
type: "POST",
url: 'default.aspx/MyPageMethod',
contentType: "application/json; charset=utf-8",
data: "{msg:'" + msg +"'}",
dataType: "json",
success: function(result){alert(result.d);},
error: function(result){alert(result.d);}
});

}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Call Page Method" OnClientClick="CallPageMethod(); return false;" />
<asp:Button ID="Button2" runat="server" Text="Postback" onclick="Button2_Click" />
</form>
</body>
</html>


code-behind:



protected string Message;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Message = "hellooo";
}
}

[System.Web.Services.WebMethod]
public static string MyPageMethod(string msg)
{
return msg;
}

protected void Button2_Click(object sender, EventArgs e)
{

}



Share/Save/Bookmark

Tuesday, October 6, 2009

Httphandler to retrive data and return it in JSON format

using System.Web.Script.Serialization;

///
/// Created by Wilmer F. Pascual
///
public class getdata : IHttpHandler
{
const string JSON_ARRAY = "[{0}]";
const string JSON_RECORD = "{{0}}";
const string JSON_KEYVALUE = "\"{0}\":\"{1}}\"";
const string COMMA = ",";

///
/// Retrieve Subcategories for the specified Category
///
///
void GetSubCategories(HttpContext context)
{
int parentCategoryId = int.Parse(context.Request.QueryString[Classes.Constants.QS_CATID]);
IEnumerable subCats = Classes.SubCategory.GetAll(parentCategoryId);
JavaScriptSerializer jSer = new JavaScriptSerializer();
string jsonData = jSer.Serialize(subCats);

context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Write(jsonData);
context.Response.End();
}

public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString[Classes.Constants.QS_CATID] != null)
{
GetSubCategories(context);
}
}

public bool IsReusable
{
get
{
return false;
}
}
}



....
the data return can then be used by jquery (ex. used in cascading dropdown list Category -> Subcategories)

$(document).ready(function()
{
$("#").change(function()
{
$("#").html("");
$("#").attr("disabled", "disabled");
$("#").append($("").val('').html('loading...'));
var catId = $("#").attr("value");
if(isNaN(catId)) return;
$.getJSON('http://?catid=' + catId, function(sucats)
{
$("#").html("");
$.each(sucats, function() {
$("#").append($("").val(this['CategoryId']).html(this['CategoryName']));
});
});
$("#").attr("disabled", "");
})
});


Share/Save/Bookmark