日期:2014-05-16  浏览次数:20263 次

C#和JavaScript交互

1.如何在JavaScript访问C#函数?
2.如何在JavaScript访问C#变量?
3.如何在C#中访问JavaScript的已有变量?
4.如何在C#中访问JavaScript函数?

?

问题1:如何在JavaScript访问C#函数?
方法一:页面和页面类相结合

1、函数声明为public????????????

??? ?后台代码(把public改成protected也可以)
??? ?public string ss()
??? ?{
??? ??? return("a");
??? ?}

2、在html里用<%=ss()%>可以调用//是C#中后台的函数名称

??? ?前台脚本
??? ?<script language=javascript>
??? ??? var a = "<%=ss()%>";//JavaScript中调用C#后台的函数
??? ??? alert(a);
??? ?</script>

?

方法二: JavaScript异步调用定义在ASP.Net页面中的方法??
??? 1.将该方法声明为公有(public);??
??? 2.将该方法声明为类方法(C#中的static,VB.NET中的Shared),而不是实例方法;??
??? 3.将该方法添加【WebMethod】属性??
??? 4.将页面中ScriptManager控件的EnablePageMethods属性设置为true;??
??? 5.在客户端使用如下JavaScript语法调用该页面方法??
??? ??? PageMethods.[MethodName](param1,param2,...,callbackFunction);??
??? 6.为客户端异步调用指定回调函数,在回调函数中接受返回值并进一步处理;??
??? 7.添加 using System.Web.Services;?

?

前台JavaScript代码

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

    <script type="text/javascript">
    function JsCallCSharp(param1)
    {            
      PageMethods.sayhell(param1,onSayHelloSucceeded);
//sayhell是后台标注了【webMethod】属性的方法 param1是传入该方法的参数,onSayHelloSucceeded是回调函数主要是对后台返回的结果进一步处理
    }        

    function onSayHelloSucceeded(result)//绑定的回调函数 
    { 
    alert(result);
    } 

    </script>

</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">

//ScriptManager控件管理脚本的,注意设置EnablePageMethods="true"此属性
    </asp:ScriptManager>
    <div>
        <input type="button" onclick="JsCallCSharp('hello')" />
    </div>
    </form>
</body>
</html>

?后台代码:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {      

    }

    [WebMethod]//标示为web服务方法属性
    public static  string sayhell(string say)//注意函数的修饰符,只能是静态的
    {
        return say;
    }
}

?

方法三: JavaScript异步调用定义在Web服务类中的方法

1.添加一个web服务标示该服务为 允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务
?对应属性为[System.Web.Script.Services.ScriptService]
2.将该方法声明public并将该方法标示为[webMethod]属性方法?
3.在页面中ScriptManager控件并添加web服务引用 <Services><asp:ServiceReference Path="~/WebService.asmx" /></Services>??
4.在客户端使用如下JavaScript语法调用web服务方法

//Webservice是web服务页面名称 HelloWord为web服务页面类中的方法,function为回调JavaScript函数主要是处理返回的结果
?WebService.HelloWorld("helloWord",function(res)??? ??? ???
???? {
??? ??? alert(res);
???? });??

?

前台JavaScript代码:

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

    <script type="text/javascript">
    function JsCallCSharp(param1)
    {            
      PageMethods.sayhell(param1,onSayHelloSucceeded);
    }        
    function onSayHelloSucceeded(result)
    { 
        alert(result);
    }  

//该方法为调用的函数
    function JsCallWebService()
    {
      WebService.HelloWorld("helloWord",function(res)//调用web服务
     {
           alert(res);
     });
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <