Thứ Tư, 1 tháng 8, 2012

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
?
code
1
2
3
4
5
6
7
8
9
10
<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

?
code
1
2
<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

?
code
1
2
3
4
5
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

Không có nhận xét nào: