代码改变世界

Javascript与C#相互调用

2013-07-03 20:47  昨日书  阅读(293)  评论(0编辑  收藏  举报

javascript调用C#代码

前台js调用后台代码方法,此方法只适用于后台方法的修饰符为public或protected,如果是其他修饰符会报错。

>后台C#代码:

1     protected int Add(int x, int y)
2     {
3         return x + y;
4     }

 >前台JS代码:

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default7.aspx.cs" Inherits="Default7" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 <html xmlns="http://www.w3.org/1999/xhtml">
 5 <head runat="server">
 6     <title></title>
 7     <script type="text/javascript">
 8         function m() {
 9             var x = "<%=Add(6,4) %>";
10             alert(x);
11         }
12     </script>
13 </head>
14 <body>
15     <form id="form1" runat="server">
16     <div>
17         <a href="javascript:void(0);" onclick="m()">JS调用C#代码</a>
18     </div>
19     </form>
20 </body>
21 </html>

C#代码调用javascript

>后台C#代码

1     protected void btnSubmit_Click(object sender, EventArgs e)
2     {
3         Page.ClientScript.RegisterClientScriptBlock(ClientScript.GetType(), "m", "<script>m(); </script>");
4     }

>前台JS代码:

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default7.aspx.cs" Inherits="Default7" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 <html xmlns="http://www.w3.org/1999/xhtml">
 5 <head runat="server">
 6     <title></title>
 7     <script type="text/javascript">
 8         function m() {
 9             alert("火云邪神超神!");
10         }
11     </script>
12 </head>
13 <body>
14     <form id="form1" runat="server">
15     <div>
16         <asp:Button ID="btnSubmit" runat="server" Text="C#调用JS" OnClick="btnSubmit_Click" />
17     </div>
18     </form>
19 </body>
20 </html>

结语

说句实话,在.net方面真是个菜,貌似这种调用有三四种方法,可是我就会这种,学的多额。大神看见不要笑哦,IT小菜鸟成长ing