Skip to main content
 首页 » 编程设计

c#之从 WebMethod 传递参数到 Jquery

2024年01月28日27三少

我有以下 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?

感谢您的帮助和时间

请您参考如下方法:

您需要在 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 返回 Url 中您可以执行此操作(但是当报告为空时您可能需要回退):

success: function (data) { 
    location.href = data; 
},