Lấy, Get datatable từ ashx trả về trong javascript sử dụng ajax trong c# asp.net

Thảo luận trong 'Lập trình web Asp.net' bắt đầu bởi admin, 3/11/16.

  1. admin
    Tham gia ngày:
    22/5/13
    Bài viết:
    4,883
    Đã được thích:
    1,193
    Điểm thành tích:
    113
    Giới tính:
    Nam
    Hôm nay ITSEON hướng dẫn các bạn cách lấy, GET datatable từ file ashx trả về trong javascript sử dụng ajax trong c# asp.net.

    Việc lấy dữ liệu từ file ashx truyền vào các tập tin usercontrol hoặc masterpage hoặc tập tin aspx trở lên dễ dàng và linh động hơn.

    Trước đây khi Rewite URL bạn sử dụng ajax load lên sẽ khó khăn vì đường dẫn URL bị rewite không được được và dẫn tới báo lỗi. Với tập tin ashx này bạn có thể thao tác dễ dàng.

    Cách sử dụng như sau nhé:

    Bước 1: khai báo 1 trang file product.aspx

    Mã:
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>lấy datatable từ ashx trả về trong javascript sử dụng ajax trong c# asp.net</title>
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
        <script type="text/javascript">
    
            $(document).ready(function () {
                $('[id$=ddPeriod]').change(function () {
                    $.ajax({
                        type: "GET",
                        datatype: 'json',
                        url: "loaddata.ashx",
                        data: "Period=" + $(this).val(),
                        success: function (data) {
                            $("#container tr+tr").remove();
                            var table = $("#container");
                            $(data).each(function (i) {
                                table.append($("<tr>").append($("<td>").html(data[i].MaterialName)).append($("<td>").html(data[i].QuantityType)));
                            });
                        },
                        error: function (f, d, s) {
                            debugger
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <h1>lấy datatable từ ashx trả về trong javascript sử dụng ajax trong c# asp.net - itseovn.com</h1>
        <select id="ddPeriod">
            <option value="P01">P 1</option>
            <option value="P02">P 2</option>
            <option value="P03">P 3</option>
            <option value="P04">P 4</option>
        </select>
        <table id="container">
            <tr>
                <th>
                    Tên sản phẩm
                </th>
                <th>
                    Kiểu giá sản phẩm
                </th>
            </tr>
        </table>
        </form>
    </body>
    </html>
    
    Bước 2: tạo tập tin Handler ashx có tên loaddata.ashx
    Mã:
    using System;
    using System.Collections;
    using System.Configuration;
    
    namespace WebInfoAS
    {
          /// <summary>
          /// Summary description for MoreProduct
          // </summary>
      public class loaddata : IHttpHandler
      {
    
         public void ProcessRequest(HttpContext context)
         {
              context.Response.ContentType = "application/json";
              string period = context.Request.QueryString["Period"];
              System.Collections.Generic.List<MaterialEntity> objList = new System.Collections.Generic.List<MaterialEntity>();
              for (int i = 0; i < 10; i++)
              {
                  objList.Add(new MaterialEntity()
                 {
                       MaterialName = "MaterialName " + period + " " + i.ToString(),
                       QuantityType = "QuantityType " + period + " " + i.ToString()
                 });
             }
             System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
             string sJSON = oSerializer.Serialize(objList);
              context.Response.Write(sJSON);
            }
    
            public bool IsReusable
            {
                  get
                 {
                       return false;
                  }
             }
       }
    }
    
    Bước 3: tạo 1 file class tên MaterialEntity.cs
    Mã:
    using System;
    namespace WebCode
    {
          public class MaterialEntity
          {
               public string MaterialName { get; set; }
               public string QuantityType { get; set; }
           }
    }
    
    Như vậy là xong, chạy và xem kết quả nhé
     
    Cảm ơn đã xem bài:

    Lấy, Get datatable từ ashx trả về trong javascript sử dụng ajax trong c# asp.net