当前位置: 代码迷 >> JavaScript >> C#跟JavaScript交互
  详细解决方案

C#跟JavaScript交互

热度:598   发布时间:2013-12-26 00:35:35.0
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">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" >
   <Services><asp:ServiceReference Path="~/WebService.asmx" /></Services>//注意要引用web服务
    </asp:ScriptManager>
    <div>
        <input type="button" onclick="JsCallCSharp('hello')" value="测试C#后台页" />
        <input type="button" onclick="JsCallWebService()" value="测试web后台类" />
    </div>
    </form>
</body>
</html>

?

后台代码:

/// <summary>
///WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 
 [System.Web.Script.Services.ScriptService]//注意要添加该标示
public class WebService : System.Web.Services.WebService {

    public WebService () {
        //如果使用设计的组件,请取消注释以下行 
        //InitializeComponent(); 
    }

    [WebMethod]//方法要标示的属性
    public string HelloWorld(string result) {
        return result;
    }
    
}

?

问题2: 如何在JavaScript访问C#变量
方法一:1、通过页面上隐藏域访问<input id="xx" type="hidden" runat="server">
方法二:1、如后台定义了PUBLIC STRING N;前台js中引用该变量的格式为'<%=n%>'或"+<%=n%>+"
方法三:1、或者你可以在服务器端变量赋值后在页面注册一段脚本
???? "<script language='javascript'>var temp=" + tmp + "</script>"
??? tmp是后台变量,然后js中可以直接访问temp获得值。

?

问题3 .如何在C#中访问JavaScript的已有变量?
方法一:前台使用服务器文本控件隐藏域,将js变量值写入其中;后台直接通过控件id访问和调用
方法二:可以用cookie或session存储变量值,后台直接使用

问题4 C#代码执行JavaScript函数和调用JavaScript函数
方法一:尽量少用Response.Write(< script>< /script>);这种方法,它会影响CSS导致页面效果偏差
方法二:C#中使用ScriptManager.RegisterStartupScript(this, this.GetType(), "edit", "CSharpCallJs('"+param1+"','"+param2+"')",
示例:
脚本函数
function CSharpCallJs(param1,param2)??
??????? {??
??????????? alert(param1 + param2);??
??????? }?

页面后台代码
ScriptManager.RegisterStartupScript(this, this.GetType(), "edit", "CSharpCallJs('" + param1 + "','" + param2 + "');", true);//关键代码调用页面脚本函数的代码

方法三:C#中使用 Page.RegisterStartupScript("ggg","<script>CSharpCallJs“”+param1+“,"+param2+“);"</script>");

方法四:C#中使用Literal类(类似label类)
示例代码
private void Button2_Click(object sender, System.EventArgs e)
{
??? string str;
??? str="<script language='javascript'>";
??? str+="selectRange()";
??? str+="</script>";
??? //Literal1.Visible=true;
??? Literal1.Text=str;

?

?

?

?

  相关解决方案