Skip to main content
 首页 » 编程设计

c#之使用 Javascript 时 C# 中的命名空间

2024年02月23日35kenshinobiy

我正在尝试使用 C# 和 javascript 自学 AJAX/Web 服务。我认为我遇到了命名空间问题,从我所做的 Google 搜索来看。

首先是我的代码:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Services; 
 
namespace SimpleAJAX 
{ 
 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)]  
    [System.Web.Script.Services.ScriptService] 
    public class WebService1 : System.Web.Services.WebService 
    { 
 
        [WebMethod] 
        public string GetServerResponse(string callerName) 
        { 
            if (callerName == string.Empty) 
                throw new Exception("Web Service Exception: invalid argument"); 
 
            return string.Format("Service responded to {0} at {1}", callerName, DateTime.Now.ToString()); 
        } 
 
    } 
} 

网络服务。

<head id="Head1" runat="server"> 
    <title>Web Service call from client-side JavaScript</title> 
 
    <script language="javascript" type="text/javascript"> 
        function SendRequest() { 
            MySampleService.GetServerResponse(form1.MyTextBox.value, OnComplete, OnError, OnTimeOut); 
        } 
 
        function OnComplete(arg) 
        { 
            alert(arg); 
        } 
 
        function OnTimeOut(arg) 
        { 
            alert("timeOut has occured"); 
        } 
 
        function OnError(arg) 
        { 
            alert("error has occured: " + arg._message); 
        } 
    </script> 
 
</head> 
<body> 
    <form id="form1" runat="server"> 
        <asp:ScriptManager ID="ScriptManager1" runat="server"> 
            <Services> 
                <asp:ServiceReference Path="~/WebServices/MySampleService.asmx" /> 
            </Services> 
        </asp:ScriptManager> 
        <div> 
            <input type="text" value="" id="MyTextBox" /> 
            <input type="button" value="Send Request to the Web Service" id="RequestButton"  
                onclick="return SendRequest()" /> 
        </div> 
    </form> 
</body>      

aspx 页面。

取自(http://www.semenoff.dk/en/Code-Corner/ASP.Net.AJAX/WebService-From-JavaScript.aspx)

当我运行它时,出现“'MySampleService' 未定义”错误。我完全按照教程进行了操作,但显然我仍然做错了什么。帮助不大?谢谢!

请您参考如下方法:

您需要在调用中包含您的命名空间和服务的实际类名:

SimpleAJAX.WebService1.GetServerResponse(form1.MyTextBox.value, OnComplete, OnError, OnTimeOut); 

要查看 ASP.NET 为您的 ScriptReference 生成的 JavaScript 代理的确切结构,请在浏览器中打开 WebService1.asmx/jsdebug。