我正在为客户开发一个网页,要求免除某些要求。有一个包含14个CheckBox的列表,每个CheckBox都有两个后续的Checkbox。检查其中哪些选项的代码将放在提交按钮中。这个方法在后面的代码中。这是代码(到目前为止)
[WebMethod]
public 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.");
}
}
}
我收到错误“非静态字段,方法或属性所需的对象引用...”
在aspx页面中,我有按钮和调用代码隐藏中的按钮的javascript / ajax。如图所示:
<table width='750' align='center'>
<tr>
<td align='left'>
<label>Please Provide your email address:</label>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align='left'>
</td>
</tr>
<tr>
<td align='left'>
<fieldset id="Fieldset">
<button onclick="SendForm();">
Send</button>
<button onclick="CancelForm();">
Cancel</button>
</fieldset>
</td>
</tr>
</table>
</form>
<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>
答案 0 :(得分:1)
据我所知,除非您明确地将“Page”对象的引用传递给您编写的Web方法,否则不能在静态方法中引用页面的控件。
答案 1 :(得分:0)
您有以下代码:
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 */
}
为什么不在项目中的类中使用此验证代码..是否有原因导致您尝试使用此代码访问PageControls
if (IsValidEmailAddress(email))
{
for (int i = 1; i <= count; i++)
{
CheckBox chkBox = chkDesc1.Checked;
}
}
更改你的for循环并开始i = 0并将&lt; = 14更改为&lt; 13 C#基于0 放置整个方法签名..您可能正在尝试在应用程序内部调用非静态方法,无论是向方法添加单词static还是删除,但我宁愿看看如何创建方法..还在哪里创建WebMethod类对象的实例..?