【问题标题】:Is there a way to drop static declaration from page method?有没有办法从页面方法中删除静态声明?
【发布时间】:2012-01-26 10:04:06
【问题描述】:

对于我正在开发的网站,我有两个 html 按钮,而不是 ASP,因为我不希望它们回发。对于提交按钮,我正在调用一个实现 PageMethods 的 javascript 函数,以从代码隐藏中调用 C# 方法。这是按钮和 javascript 的代码。

<fieldset id="Fieldset">
    <button onclick="SendForm();">Send</button>             
    &nbsp;
    <button onclick="CancelForm();">Cancel</button>                  
</fieldset>

<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />

<script type="text/javascript">
    function SendForm() {
        var email = $get("txtEmail").value;

        PageMethods.SendForm(email, OnSucceeded, OnFailed);
    }

    function OnSucceeded() {
        $get("Fieldset").innerHTML = "<p>Thank you!</p>";
    }

    function OnFailed(error) {
        alert(error.get_message());
    }
</script>

此处显示的代码隐藏方法:

[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.");
        }
    }
}

除非它被声明为静态,否则它不起作用。将其声明为静态会阻止我检查页面上的复选框,因为它会生成“非静态字段、方法或属性需要对象引用”错误。所以我的问题可以从两个方向中的任何一个来解决。 A)有没有一种方法可以让这种方法工作而不将其声明为静态? B)如果方法是静态的,我如何检查复选框。

【问题讨论】:

    标签: c# javascript .net static webforms


    【解决方案1】:

    页面方法是传统 ASMX Web 服务技术的一个特例。它们允许您将服务放置在页面的代码隐藏类中,并使您无需为该服务创建一个单独的项目。

    但他们将永远无法访问页面本身的任何内容。您必须从客户端执行此操作,并将复选框的值传递给服务。

    【讨论】:

      【解决方案2】:

      如果您需要检查复选框,那么您需要使用 UpdatePanel 来执行 AJAX 操作,或者从您的页面方法(理想情况下为字符串)返回一些内容,然后根据客户端上的 javascript 返回的内容检查复选框。

      【讨论】:

        【解决方案3】:

        它必须是静态的,没有办法解决;但是你可以像这样访问页面

        Page page = HttpContext.Current.Handler as Page;
        

        并在此页面实例上执行 FindControl。

        desc[i] = ((CheckBox)page.FindControl("chkDesc" + i.ToString())).Checked;
        

        【讨论】:

          猜你喜欢
          • 2013-04-01
          • 2019-11-12
          • 2020-03-18
          • 2016-12-16
          • 1970-01-01
          • 2013-11-28
          • 2014-10-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多