简体   繁体   中英

How to refer to a method in the inline code from the code-behind file?

The IsPrime method should be in a separate class in the App_Code folder, but I want to understand why this doesn't work and how to make it work.

The build error is in default.cs: "The name 'IsPrime' does not exist in the current context"

构建错误

Here is the code behind, default.cs:

using System;
public partial class _Default : System.Web.UI.Page {
    protected void btnGo_Click(object sender, EventArgs e) {
        lblAnswer.Text = IsPrime(Convert.ToInt32(txtNumber.Text));
    }
}

Here is the markup, default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<%@ Import Namespace="System" %>
<%@ Page Language="c#"%>

<script runat="server">
    public partial class _Default : System.Web.UI.Page {
        static public Boolean IsPrime(int num) {
            Boolean isPrime = true;
            int limit = num / 2;
            for (int i = 2; i < limit; i++) {
                if (num % i == 0) { isPrime = false; break; }
            }
            return isPrime;
        }
    }
</script>

<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
    </div>
    <div>
        <asp:Button runat="server" ID="btnGo" OnClick="btnGo_Click" Text="Go" />
    </div>
    <div>
        <asp:label runat="server" ID="lblAnswer" />
    </div>

    </form>
</body>
</html>

I changed the reference to IsPrime in Default.cs to

default_aspx.IsPrime(...)

Evidently the inline code is put in a class called default_aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM