user6558380
user6558380

Reputation:

If statement Invalid in aspx files

I have this aspx code:

<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>

But im getting this error:

error CS1519: Invalid token 'if' in class, struct, or interface member declaration

I want to run the function just if the value is > 0. How could I fix it? thanks

Upvotes: 0

Views: 114

Answers (1)

mason
mason

Reputation: 32702

You have mixed JavaScript and C# code together. They don't go hand in hand. The C# executes on the server before the HTML and JS is event sent to the client (where the JavaScript executes). You should use C# to get the solarValue instead of JavaScript.

Also, in C# you can't have an if statement outside of a method body. You can move the if statement inside your method body to resolve the error.

<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>

You should also remove the empty catch block. At least log exceptions, don't silently swallow them.

Note that modern practice is to place any C# code in a separate file called a code behind. It will make the distinction between JavaScript and C# a little more distinct.

Upvotes: 1

Related Questions