首页 > 解决方案 > 使用 WebMethod 将 POCO 对象列表解析为 javascript

问题描述

我有一个获取 ajax 调用:

function TraerInstructivos() {
    $.ajax({
        type: "GET",
        url: '<%= Page.ResolveUrl("~/Instructivo/Instructivos.aspx") %>' + '/TraerInstructivos',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {

            $.each(result, function (i, item) {
                alert(item.DescripcionVideo);
                alert(item.DireccionVideo);
            });
        },
        error: function (response) {
            alert("Error");
        }
    });
};

这在我的 aspx 中调用了以下 webmethod:

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static List<InstructivoDTO> TraerInstructivos()
{
    try
    {
        return Controles_Instructivo_Instructivos.TraerInstructivos();

    }
    catch (Exception ex)
    {
        throw ex;
    }

}

这在我的 ascx 中调用了一段代码:

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static List<InstructivoDTO> TraerInstructivos()
{
    List<InstructivoDTO> lstResponse = new List<InstructivoDTO>();

    WC.InstructivoDTOResp response = new WC.InstructivoDTOResp() { ListaDeInstructivos = new WC.ListaDeInstructivos() };

    //Traigo los instructivos
    WC.InstructivoDTOReq request = new WC.InstructivoDTOReq()
    {
        TipoOperacion = WC.Accion.Consultar,
        Operacion = Constantes.Consultas.Instructivos.TRAER_INSTRUCTIVOS_WEB_COMERCIO,
        ListaDeInstructivos = new WC.ListaDeInstructivos()
    };

    using (WC.FacturaClient fc = new WC.FacturaClient())
    {
        response = fc.InstructivosEjecutar(request);
    }

    foreach (var i in response.ListaDeInstructivos)
    {
        lstResponse.Add(new InstructivoDTO()
            {
                DescripcionVideo = i.DescripcionVideo,
                DireccionVideo = i.DireccionVideo,
                EsBackOffice = i.EsBackOffice
            });

    }

    return lstResponse;
}

它返回一个 POCO 对象或 DTO 的列表,真的很简单,它有 3 个属性,其中 2 个是字符串类型,另一个是布尔类型。

在我的 ajax 调用的警报函数中,我看到我收到“未定义”作为结果。

我错过了什么吗?我试过了stringifyJSON.Parse(response.d)上面写着“无效字符”。

编辑:

感谢 HaukurHaf 的响应,我更改了 jquery 中的 for 循环,看来,当我进行一些测试时,我更改了它,所以我的 Ajax 是:

<script type="text/javascript">
    $(document).ready(function () {
        TraerInstructivos();
    });

    function TraerInstructivos() {
        $.ajax({
            type: "GET",
            url: '<%= Page.ResolveUrl("~/Instructivo/Instructivos.aspx") %>' + '/TraerInstructivos',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {

                $.each(response, function (i, item) {
                    alert(item.DescripcionVideo);
                    alert(item.DireccionVideo);
                });
            },
            error: function (response) {
                alert("Error");
            }
        });
    };

</script>

仍然未定义,这是有趣的部分,如果我将一个 console.log 而不是警报放在我的整个对象中,我可以用我放在表中的值看到它:

在此处输入图像描述

标签: javascriptc#webmethod

解决方案


我找到了答案。

看来我缺少整个解决方案的另一半。它不起作用的原因是因为我说我将 Json 对象返回给 ajax 调用,而是我返回对象而不序列化它们。所以现在的代码是这样的:

ASPX:

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string TraerInstructivos()
{
    try
    {
        List<InstructivoDTO> response = Controles_Instructivo_Instructivos.TraerInstructivos();
        var json = new JavaScriptSerializer().Serialize(response);
        return json;
    }
    catch (Exception ex)
    {
        throw ex;
    }

}

AJAX 调用:

function TraerInstructivos() {
    $.ajax({
        type: "GET",
        url: '<%= Page.ResolveUrl("~/Instructivo/Instructivos.aspx") %>' + '/TraerInstructivos',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var res = JSON.parse(response.d);
            $.each(res, function (i, item) {
               alert(item.DescripcionVideo);
            });
        },
        error: function (response) {
            alert("Error");
        }
    });
};

推荐阅读