【问题标题】:Ajax in asp web forms doesn't get calledASP Web 表单中的 Ajax 不会被调用
【发布时间】:2016-12-14 03:40:06
【问题描述】:

我有很多按钮,当用户单击一个时,我希望它使用 ajax 更新标签。

我在我的模板中实现了 ajax,如下所示:

<form runat="server">
    <asp:ScriptManager ID="ScriptManagerPull" runat="server"> 
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <div runat="server" id="SiteContent">
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
</form>

按钮是动态生成的;

foreach (MyDTO myDTO in List) {
    Button ButtonPull = new Button();
    ButtonPull.Text = "Pull";
    ButtonPull.ID = articleDTO.ArticleID.ToString();
    ButtonPull.ControlStyle.CssClass = "btn btn-default";
    ButtonPull.Click += new EventHandler(Pull_Click);
    SiteContent.Controls.Add(ButtonPull);
}

现在的问题是当用户点击按钮时事件没有被调用。这不起作用:

protected void Pull_Click(object sender, EventArgs e) {
    // Button button = sender as Button;
    LabelTest.Text = "Cool";  
}

我该怎么做?

谢谢。

【问题讨论】:

  • 您是否在表单中看到浏览器中的动态按钮?
  • 是的,我看到了。
  • 很抱歉赶上了一些事情。我已经发布了答案。

标签: asp.net ajax webforms


【解决方案1】:

我假设您不只是想调用点击事件,还可能通过 AJAX 将一些数据从客户端传递到服务器。最直接的方法是,没有ScriptManagerUpdatePantel 和所有类似的东西。我创建了一个按钮,它在服务器端没有单击事件处理程序。但它在客户端有一个。

protected void Page_Load(object sender, EventArgs e)
{
    Button ButtonPull = new Button();
    ButtonPull.Text = "Pull";
    ButtonPull.ID = "Button1";
    ButtonPull.ControlStyle.CssClass = "btn btn-default";
    this.Form.Controls.Add(ButtonPull);

    // You can pass anything you want to the server. Here I am passing 1111
    // You can pass things from the client side as well. Whole JSON objects as well
    ButtonPull.OnClientClick = "callServer(1111);return false;"; // return false so button does not postback
}

我也将此方法添加到我的页面代码后面。这是一个 Web 方法,它接收一个 id 为 int 并将其附加到一个字符串并将该字符串返回给客户端。

[WebMethod]
[ScriptMethod(UseHttpGet = true,
ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public static string GetStuffFromServer(int id)
{
    return "Works like a charm! And id is " + id ;
}

最后将此添加到我的视图中。当在客户端点击按钮时,它会调用这个函数并按照我们在上面创建按钮时的指示传递1111。在这个函数中,我们使用 jQuery ajax 调用来调用服务器方法GetSuffFromServer。如果一切顺利,服务器将返回,我们将在这里成功并提醒服务器返回的数据。同样,服务器可以返回任何需要的东西。而且这个方法可以将任何需要的东西发送到服务器。

<script>
    function callServer(id) {
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "default.aspx/GetStuffFromServer?id=" + id,
            success: function (data)
            {
                alert(data.d);
            },
            error: function (data) { alert(data);}
        });
    }
</script>

App_Start 文件夹的 RouteConfig.cs 文件中的最后一件事更改了这一行:

settings.AutoRedirectMode = RedirectMode.Permanent;

到这里:

settings.AutoRedirectMode = RedirectMode.Off; 

这个变化是因为我在调用web方法时使用了一个友好的url:default.aspx/GetStuffFromServer?id=

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 2016-05-03
    相关资源
    最近更新 更多