zoukankan      html  css  js  c++  java
  • ASP.NET学习3.前端和后台的相互调用

    1.前端的HTML服务器控件中调用前端的js

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ShowMessageBox._Default" %>

    <!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>MESSAGEBOX</title>

        <script type="text/javascript">

            function test2() {
                alert("这是为什么呢");
            }
        </script>
    </head>
    <body>
        <button id="button" onclick="test2()">调用js</button>

    </body>
    </html>

    2.Web服务器控件调用js函数

    这个貌似做不到? Button2调用上面的test2()方法:

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

        <script type="text/javascript">

            function test2() {
                alert("这是为什么呢");
            }
        </script>
    </head>
    <body>
        <form runat="server" >                   
          <asp:Button ID="Button2" runat="server" Text="调用前端js函数"  OnClick="test2()" ></asp:Button>
        </form>
    </body>
    </html>

    结果:

     test2()是客户端的脚本,并不存在与服务器中,不能被服务器控件调用。

    3.服务器控件调用后台C#代码(传说中的code-behind技术):

    Default.aspx的部分代码:

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

    </head>
    <body>
        <form runat="server" >          
        <asp:Button id="Button1" runat="server" Text="对话框" onclick="Button1_Click1" ></asp:Button> 

        </form>

    </body>
    </html>

    Default.aspx.cs的部分:

            protected void Button1_Click1(object sender, EventArgs e)
            {
                CallJs();    //这里再去调用前端js
            }

    4.后台C#代码调用前端中已有的js函数

    后台:

            private void CallJs()
            {
                ClientScriptManager cs = Page.ClientScript;
                cs.RegisterStartupScript(this.GetType(), "testPage", "<script>test2()</script>");
            }

    前端:

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

        <script type="text/javascript">
            function test2() {
                alert("这是为什么呢");
            }
        </script>
    </head>
    <body>  
    </body>
    </html>

    适用RegisterStartupScript方法同样可以发送一段js代码:cs.RegisterStartupScript(this.GetType(), "testPage", "<script>alert("这是为什么呢")</script>");

    2013年6月13日补充:RegisterStartupScript方法是向页面中注入脚本,并且注册的脚本只有在页面的onload事件触发时才执行。

  • 相关阅读:
    秋风下的萧瑟 NOIP2018 游记
    Dsu on Tree
    BZOJ 3812 : 主旋律
    FFT&NTT
    manacher
    Winniechen’s test1
    如何在万亿级别规模的数据量上使用Spark
    Spark运行时的内核架构以及架构思考
    hadoop离线数据存储和挖掘架构
    Hadoop平台的基本组成与生态系统
  • 原文地址:https://www.cnblogs.com/superdaddy/p/3127136.html
Copyright © 2011-2022 走看看