如何在服务器上调用脚本runat内的属性

时间:2012-04-16 23:59:29

标签: c# asp.net web

我有一个我需要在.aspx中调用的函数,并且它在一个标记中如下所示,我遇到的问题是我需要评估.cs clas中的属性。我怎么能做到这一点?。

<script type="text/javascript">
    function Redirect() {
        location.href = "homePage.aspx";
    } 
 </script> 
     <script runat="server"> 
        protected void Button1_Click(Object sender, EventArgs e)
        {
            if (something is true from the propties set in .cs)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(),
               "ConfirmBox", "if(confirm('The numbers selected are not in the directory, you wish to continue?') == true){Redirect();};", true);
            } 
        }
    </script>

2 个答案:

答案 0 :(得分:1)

您可以使用命名空间执行此操作:首先将您的类放在命名空间

namespace testNamespace
{
  public class test
    {
       public static bool tester(int x, int y)
        {
            if (x == y)
            {
                return true;
            }
            else return false;
        }
    }
}

导入命名空间使用

    <%@ Import Namespace="testNamespace" %>

<script runat="server"> 
        protected void Button1_Click(Object sender, EventArgs e)
        {
            if (test.tester(2, 2))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(),
               "ConfirmBox", "if(confirm('The numbers selected are not in the directory, you wish to continue?') == true){Redirect();};", true);
            } 
        }
    </script>

使用此脚本,您可以将值传递给类文件,验证它并返回您的答案。

答案 1 :(得分:0)

您可以在CS类中定义属性,并使用像此类

这样的Partial类来访问它

CS:

public partial class WebForm1 : System.Web.UI.Page
    {
        public bool MyProperty { get; set; }

       protected void Page_PreInit(object sender,EventArgs e)
       {
           MyProperty = true;
       }

        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }

ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script runat="server"> 
    protected void Button1_Click(Object sender, EventArgs e)
    {
        if (MyProperty)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(),
           "ConfirmBox", "if(confirm('The numbers selected are not in the directory, you wish to continue?') == true){Redirect();};", true);
        } 
    }
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button Text="text" runat="server" OnClick=Button1_Click />
    </div>
    </form>
</body>
</html>