如何从asp.net调用服务器端非静态c#函数

时间:2015-03-23 08:41:15

标签: c# asp.net ajax function server-side

我需要调用服务器端函数(C#)来向表中添加行。如果我使用普通按钮来实现这一点我自动调用回发,通过这样做我丢失了我添加到我的网页的大部分动态数据。我做了一些研究,我认为最简单的方法是实现我的目标,即在不调用回发(或至少丢失动态数据)的情况下将动态数据添加到我的网页,就是从ajax调用服务器端功能。然而,函数需要是静态的,这是不可能的。

这是我的功能:

public void onButtonPress(object sender, EventArgs e)
    {
        ContentPlaceHolder Content;
        Content = (ContentPlaceHolder)Master.FindControl("MainContent");

        switch(((Button)sender).ID)
        {
            case "FiscaleAddButton":
                // 1:Naam - 2:Adres - 3:Postcode - 4:Contact - 5:Telefoon - 6:Telefoon - 7:Mail - 8:KvK - 9:BTW - 10:Website
                TableRow row = new TableRow();
                for (int i = 1; i <= 10; i++)
                {
                    TableCell cell = new TableCell();
                    cell.Text = ((TextBox)Content.FindControl("FiscaleUnitTextBox" + i.ToString())).Text;
                    row.Cells.Add(cell);
                }
                FiscaleEenhedenTable.Rows.Add(row);
                break;
        }
    }

这是我的按钮:

<asp:Button ID="FiscaleAddButton" runat="server" CommandName="FiAdd" Text="Toevoegen" ClientIDMode="Static" OnClick="onButtonPress"/>

我已经尝试使用AJAX来调用[WebMethod],但为了使其工作,该方法需要是静态的。

AJAX代码:

function callButtonMethod() {     
       $.ajax({
           type: "POST",
           url: 'KlantToevoegen.aspx/onButtonPress',
           data: "",
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           success: function (msg) {
               $("#ContentWrapper").html("success");
           },
           error: function (e) {
               $("#ContentWrapper").html("Something Wrong.");
           }
       });
   }

如果您有任何问题,请在评论中询问他们。提前谢谢。

编辑:

[WebMethod]
    public static void onButtonPress(object sender, EventArgs e)
    {
        KlantToevoegen page = getInstance();
        ContentPlaceHolder Content;
        Content = (ContentPlaceHolder)page.Master.FindControl("MainContent");

        switch(((Button)sender).ID)
        {
            case "FiscaleAddButton":
                // 1:Naam - 2:Adres - 3:Postcode - 4:Contact - 5:Telefoon - 6:Telefoon - 7:Mail - 8:KvK - 9:BTW - 10:Website
                TableRow row = new TableRow();
                for (int i = 1; i <= 10; i++)
                {
                    TableCell cell = new TableCell();
                    cell.Text = ((TextBox)Content.FindControl("FiscaleUnitTextBox" + i.ToString())).Text;
                    row.Cells.Add(cell);
                }
                page.FiscaleEenhedenTable.Rows.Add(row);
                break;
        }
    }

0 个答案:

没有答案