从javascript调用类文件(c#中的.cs)函数,并帮助如何编写Ajax + Webservices

时间:2012-05-22 04:41:53

标签: c# javascript

这里我的简单示例代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace PopUpFromCsFile
{
    public class PopUpWindow
    {
        public void PopUpFromCsFile()
        {
         string str1 = "<script> $.ajax({" +
                     "type: 'GET'," +
                      "url: 'Service/Class1.cs/callfromjs'," +
                        "data: '{}'," + "success: function () { getDetails(); } " +
                        "});</script>";

        page.ClientScript.RegisterStartupScript(this.GetType(), "script1", str1);

        }
        [WebMetod]
        public string  CallFromJs()
        {
            return "santosh";
        }

      public void getDetails()
       {
        string str = "<script>alert('Hai');</script>";
        System.Web.UI.Page page = (System.Web.UI.Page)HttpContext.Current.Handler;
        page.ClientScript.RegisterStartupScript(this.GetType(), "script2", str);
       }
    }
}

说明

在PopUpFromCsFile()中,我为Ajax + WebMethod编写了代码。 Url路径是否正确,这里我无法从脚本调用getDetails()。

1 个答案:

答案 0 :(得分:2)

你做不到。 .cs是C#源代码文件,不能(从任何语言)按原样使用。您必须将其编译为DLL。

一旦这样做,就无法通过JavaScript与DLL通信。 JavaScript被沙箱插入您的浏览器。您需要编写(并在每台客户端PC上安装)浏览器扩展以与本机DLL进行交互。

您需要将C#代码重写为JavaScript。

相关问题