如何在文本区域中显示来自服务器的数据

时间:2018-11-21 04:50:07

标签: javascript c# jquery .net

我在C#中具有以下代码,该代码可在Dictionary中添加数据

public static Dictionary<int, string> ReadFile()
{
        Dictionary<int, string> datalist = new Dictionary<int,string>();
        var lines = File.ReadAllLines(@"C:\\temp\\Sample.txt");
        int i = 1;
        foreach (var line in lines)
        {
            datalist.Add(i, line);
            i++;
        }
        return datalist;
}

现在,我想在文本区域中逐行显示由词典分隔的字典数据。下面是我的UI代码

<button type="button" id ="GetFlatFile">Click Me!</button>

<div id ="DisplayFlatFile">

</div>

function GetFlatFileAndSetupColumn() {
        $("#GetFlatFile").click(function () {
            $.ajax({
                type: "POST",
                url: "Default.aspx/ReadFile",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                cache: false,
                success: function (jsondata) {
                    mydata = jsondata.d;
                    $('#DisplayFlatFile').empty();
                    $('#DisplayFlatFile').append(mydata);
                }, error: function (x, e) {
                    alert("The call to the server side failed. " + x.responseText);
                }
            });
        });
    }

如何做到?

1 个答案:

答案 0 :(得分:1)

首先,GetFlatFile不是<textarea>元素,而是<div>元素。假设jsondata.d包含从代码隐藏方法返回的字典值,则可以使用jQuery.each()来迭代值:

function GetFlatFileAndSetupColumn() {
    $("#GetFlatFile").click(function () {
        $.ajax({
            type: "POST",
            url: "Default.aspx/ReadFile",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            cache: false,
            success: function (jsondata) {
                mydata = jsondata.d;
                $('#DisplayFlatFile').empty();

                // iterate keys and values here
                $(mydata).each(function (key, value) {

                    // data display example
                    $('#DisplayFlatFile').append(key + ' - ' + value);

                    // line break per iteration
                    $('#DisplayFlatFile').append('<br />');

                });
            }, error: function (x, e) {
                alert("The call to the server side failed. " + x.responseText);
            }
        });
    });
}

此外,您的代码隐藏方法应标记为[WebMethod]属性:

[WebMethod]
public static Dictionary<int, string> ReadFile()
{
    Dictionary<int, string> datalist = new Dictionary<int, string>();
    var lines = File.ReadAllLines(@"C:\\temp\\Sample.txt");
    int i = 1;
    foreach (var line in lines)
    {
        datalist.Add(i, line);
        i++;
    }
    return datalist;
}

相关问题:

How to get data from C# WebMethod as Dictionary<> and display response using jquery ajax?