If语句在aspx文件中无效
本文关键字:无效 文件 aspx 语句 If | 更新日期: 2023-09-27 18:13:45
我有这个aspx代码:
<td>
<asp:TextBox ID="txtSolarValue" runat="server" Text='<%# Eval("SolarValue") %>' />
</td>
<script runat="server">
var solarvalue = document.getElementById("ctl00_maincontent_FormView1_txtSolarValue");
if (solarvalue > 0)
{
void Button2_Click(object sender, EventArgs e)
{
try
{
SendMail();
}
catch (Exception) { }
}
}
</script>
但是我得到这个错误:
error CS1519: Invalid token 'if' in class, struct, or interface member declaration
我想只在值> 0时运行函数。我怎样才能修好它呢?由于
您将JavaScript和c#代码混合在一起。它们并不同时存在。在HTML和JS事件发送到客户端(JavaScript在客户端执行)之前,c#在服务器上执行。你应该使用c#来获取solarValue
,而不是JavaScript。
同样,在c#中,你不能在方法体之外使用if语句。你可以把if语句移到方法体中来解决这个错误。
<script runat="server">
void Button2_Click(object sender, EventArgs e) //this method should be moved to code behind
{
var txtSolarValue = (TextBox) FormView1.FindControl("txtSolarValue"); //this is necessary because your TextBox is nested inside a FormView
var solarvalue = int.Parse(txtSolarValue.Text); //really need some error handling here in case it's not a valid number
if (solarvalue > 0)
{
try
{
SendMail();
}
catch (Exception) { } //do not do empty catch blocks! Log the exception!
}
}
</script>
还应该删除空catch块。至少记录异常,不要默默地吞下它们。
请注意,现代的做法是将任何c#代码放在一个单独的文件中,称为代码隐藏。它将使JavaScript和c#之间的区别更加明显。