Is there a way to remove the static statement from the page method?

For a site I’m developing I have two html buttons, not ASP because I do not want them to postback. For the submit button I am calling a javascript function that implements PageMethods to call a C# method from the codebehind. Here is the code for the buttons and the javascript.

function SendForm() { var email = $get("txtEmail").value; PageMethods.SendForm(email, OnSucceeded, OnFailed); } function OnSucceeded() { $get("Fieldset").innerHTML = "

Thank you!

"; } function OnFailed(error) { alert(error.get_message()); }

The codebehind method shown here:

[WebMethod]
public static void SendForm(string email)
{
    if (string.IsNullOrEmpty(email))
    {
        throw new Exception("You must supply an email address.");
    }
    else
    {
        if (IsValidEmailAddress(email))
        {
            bool[] desc = new bool[14];
            bool[] local = new bool[14];
            bool[] other = new bool[14];

            for (int i = 1; i <= 14; i++)
            {
                desc[i] = ((CheckBox)Page.FindControl("chkDesc" + i.ToString())).Checked;
                local[i] = ((CheckBox)Page.FindControl("chkLocal" + i.ToString())).Checked;
                other[i] = ((CheckBox)Page.FindControl("chkOther" + i.ToString())).Checked;

                /* Do stuff here */
            }
        }
        else
        {
            throw new Exception("You must supply a valid email address.");
        }
    }
}

does not work unless it is declared as static. Declaring it as static blocks me from checking the checkboxes on the page because it generates a “An object reference is required for the non-static field, method, or property” error. So my problem can be fixed from either of two directions. A) Is there a way I can have this method work without declaring it as static? B) How do I check the checkboxes if the method is static.

It has to be static, no way around that; But you can access the Page like this

Page page = HttpContext.Current.Handler as Page;

and do FindControl on this page instance.

desc[i] = ((CheckBox)page.FindControl("chkDesc" + i.ToString())).Checked;
Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Is there a way to remove the static statement from the page method&quest;

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录