프로그래밍/ASP.NET

DataTable을 Json 으로 변환하는 예시

Doonee 2014. 5. 7. 14:33
반응형

DataTable을 Json으로 변환하는 함수

.cs

    public static string ConvertDataTabletoString(DataTable dt)

    {        

        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();

        Dictionary<string, object> row;

        foreach (DataRow dr in dt.Rows)

        {

            row = new Dictionary<string, object>();

            foreach (DataColumn col in dt.Columns)

            {

                row.Add(col.ColumnName, dr[col]);

            }

            rows.Add(row);

        }

        return serializer.Serialize(rows);

    }


데이터 가져오기

    [System.Web.Services.WebMethod]

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

    public static string LoadSchedule(string indicatorseq, string orgno, string userid)

    {

        DataTable dt = PPPBiz.Exam.GetLeftBasicInfo(indicatorseq, orgno, userid, "A");

        if (dt == null || dt.Rows.Count < 1)

        {

            ShowMessage.PrintMsgBack("05011421 : 응시할 시험이 없습니다.");

        }

        return ConvertDataTabletoString(dt);

    }



화면에 뿌리기

.aspx

    <asp:ScriptManager ID="scriptManager1" runat="server" EnablePageMethods="true">

    </asp:ScriptManager>


.js

function LoadScheduleHtml(response) {

    var parsed = $.parseJSON(response.d);

    var result = '';

    $.each(parsed, function (i, jsondata) {

        var liTitle = $(document.createElement('li'));

        liTitle.append(parsed[i].BINDICATORNAME);

    });

    $('#lbSchedule').html(result);

}

function LoadSchedule() {

    $.ajax({

        type: "POST",

        url: "Schedule.aspx/LoadSchedule",

        data: '{indicatorseq: "' + $('#hdIndicatorseq').val() + '", orgno: "' + $("#hdOrgno").val() + '", userid: "' + $("#hdUserid").val() + '"}',

        contentType: "application/json; charset=utf-8",

        dataType: "json",

        success: LoadScheduleHtml,

        error: function (XHR, errStatus, errorThrown) {

            var err = JSON.parse(XHR.responseText);

            errorMessage = err.Message;

            alert(errorMessage);

        }

    });

    return false;

}

$(function () {

    LoadSchedule();

});