【问题标题】:passing parameter from WebMethod to Jquery将参数从 WebMethod 传递给 Jquery
【发布时间】:2013-08-08 14:28:03
【问题描述】:

我有以下 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#方法中的void关键字是什么意思吗?
  • 是的,我必须更改它以返回 URL,但是我不知道如何将它传递给 Jquery
  • 在更改 webmethod 后尝试在 jQuery 成功函数中检查 data 的值。
  • 我试图检查数据的值,它的对象对象
  • 做console.log(data),不是警报。

标签: c# jquery asp.net json


【解决方案1】:

您需要在 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 中你可以做(​​但是当报告为空时你可能想要一个后备):

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

【讨论】:

  • @Johann 如果你调试WebMethod,断点会命中吗?报告肯定不为空吗?
  • 是的,我得到了一个 url,刚刚调试。重定向到localhost/myapp/[object对象]
  • @Johann 在您的success 方法中data.d 中有什么内容吗?尝试提醒它。如果是这样,请使用它。
【解决方案2】:

您需要更改页面方法以实际返回某些内容,您目前通过 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;
}

如Never worry about ASP.NET AJAX’s .d again 中所述,有一些方法可以缓解这种情况

【讨论】:

  • 如果report 为空,您仍然不返回任何内容。
  • @Johann - 您的success 回调需要更改其逻辑以使用document.location.href = data; 而不是document.location.href = reportUrl;。 data 是您从 page 方法返回的内容,在本例中为 string。
  • Karl 是的,目前它的 document.location.href = data;虽然还是不行
  • 那你的reportsBll.GetReports()返回的URL的数据无效,你调试看看URL的值是多少?
  • 我正在明确获取 URL,我刚刚调试过。它重定向到这个页面localhost/myapp/[objectObject]
猜你喜欢
  • 2010-10-18
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多