Tuesday , 19 March 2024
HOT

Dùng JQuery để gọi ASP.NET Handler (ASHX)

ASP.NET Handler được dùng để trả về cho client một nội dung động từ QueryString (bạn có thể trả về dạng Image,Xml,JSON hoặc file văn bản …)

Tại sao phải sử dụng file ASHX mà không phải là ASPX?

– Nhanh hơn: khi bạn sử dụng file Ashx để trả dữ liệu về cho client sẽ nhanh hơn từ 5–>10%
khi bạn sử dụng file aspx vì file ashx chỉ sử lý 1 sự kiện duy nhất đó là ProcessRequest.

Viết Code JQuery để post dữ liệu lên ASHX

<script language="javascript" type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script language="javascript" type="text/javascript">
$(function () { 
$("#btnSay").click(function () 
{
 $.post("Hello.ashx", 
{ txtName: $("#txtName").val() }, function (result) { alert(result); });        
});    
})
;</script>

Html Code

<input type="text" name="txtName" id="txtName" /><input type="button" name="btnSay" id="btnSay" value="Say" />

Viết Code trong file ASHX để trả dữ liệu về cho client

public void ProcessRequest(HttpContext context)
{
  context.Response.ContentType = "text/plain";    
  context.Response.Write("Hello " + context.Request["txtName"]);
}

Kết quả khi click vào nút btnSay

Source : dev[dot]meotom[dot]net

Leave a Reply

Your email address will not be published. Required fields are marked *

*