1

我有以下 WebMethod :-

        [WebMethod(EnableSession = true)]
    public static void OpenReport(string reportName)
    {
        Report report = reportsBll.GetReports().FirstOrDefault(x => reportQuestion != null && x.Id == reportQuestion.ReportId);

        if (report != null) reportUrl = report.Url;
    }

现在我希望将 report.Url 传递给这个 Jquery 方法:-

    $('.ReportButton').click(function () {
    var args = { reportName : '' };

    $.ajax({
        type: "POST",
        url: "ReportsByQuestionsDetails.aspx/OpenReport",
        data: JSON.stringify(args),
        contentType: "application/json;charset=utf-8;",
        success: function (data) {
            alert('success');
            document.location.href = reportUrl;
        },
        error: function () {
        }
    });
});

如何将 reportUrl 从 WebMethod 传递给 Jquery?

感谢您的帮助和时间

4

2 回答 2

5

您需要在C# 方法中返回:string

[WebMethod(EnableSession = true)]
public static string OpenReport(string reportName)
{
    string reportUrl = string.Empty;
    Report report = reportsBll.GetReports().FirstOrDefault(x => reportQuestion != null && x.Id == reportQuestion.ReportId);

    if (report != null) reportUrl = report.Url;

    return reportUrl;
}

然后在您的 ajax return Url 中,您可以执行以下操作(但是,当报告为 null 时,您可能需要回退):

success: function (data) {
    location.href = data;
},
于 2013-08-08T14:30:55.510 回答
1

您需要更改您的页面方法以实际返回某些内容,您目前通过void返回类型没有返回任何内容,请将其更改为:

[WebMethod(EnableSession = true)]
public static string OpenReport(string reportName)
{
    Report report = reportsBll.GetReports().FirstOrDefault(x => reportQuestion != null && x.Id == reportQuestion.ReportId);

    if (report != null)
    { 
        return report.Url;
    }

    return String.Empty;
}

更新:微软在 ASP.NET AJAX 3.5 中为 JSON 响应添加了一个父容器,以对抗潜在的跨站点脚本 (XSS) 攻击;因此你success的回调需要是这样的:

success: function (data) {
    alert('success');
    document.location.href = data.d;
}

不再担心 ASP.NET AJAX 的 .d中所述,有一些方法可以缓解这种情况

于 2013-08-08T14:31:20.070 回答