【问题标题】:calling a c# function from javascript dosent work从 javascript 调用 c# 函数不起作用
【发布时间】:2013-03-09 22:23:53
【问题描述】:

我正在用 c# 在 asp.net 中构建一个 WebApplication,但在从 JS 调用 c# 函数时遇到问题。

我的代码是这样的:

在js中:

Function doStuff()
{
    var service = new seatService.Service1();
    service.DoWork(id, onSuccess, null, null);
}

在服务页面中是:

[ServiceContract(Namespace = "seatService")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 
{
    [OperationContract]
    public static  void DoWork(string id)
    {
      //here there is a function that calls the DB
    }
}   

奇怪的是,它实际上工作了 20 次(使用相同的代码),但大多数时候它都失败了,我收到了消息:

未捕获的referenceEror - 未定义座位服务。

状态码为500 Internal Server Error.

因为它有时工作有时不工作 - 我的问题在哪里?

【问题讨论】:

  • 您提供的错误信息不足。错误 500 可能有很多选择。您需要使用开发人员工具调试页面并使用网络捕获捕获来自服务器的响应正文,您将看到更清晰的错误信息。请参阅此处示例如何在 Internet Explorer 中执行此操作:msdn.microsoft.com/en-us/library/gg130952(v=vs.85).aspx
  • Function 在您的 JavaScript 代码中应为 function(小写)
  • 我这样做了,但是当我查找响应正文时,它说没有要显示的数据。响应头是:Key Value Response HTTP/1.1 500 Internal Server Error Server ASP.NET Development Server/10.0.0.0 Date Sat, 09 Mar 2013 22:50:06 GMT X-AspNet-Version 4.0.30319 Cache-Control private Content - 输入文本/html; charset=utf-8 Content-Length 9527 连接关闭
  • 小写。只是在这里错误地以大写 f 开头。

标签: c# asp.net web-applications


【解决方案1】:

您想为此使用PageMethods。下面是一些示例代码来演示:

public partial class ContactUs : System.Web.UI.Page
{
   [WebMethod]
   public static void SendForm(string name, string email, string message)
   {
       if (string.IsNullOrEmpty(name))
           throw new Exception("You must supply a name.");    
       if (string.IsNullOrEmpty(email))
           throw new Exception("You must supply an email address.");   
       if (string.IsNullOrEmpty(message))
           throw new Exception("Please provide a message to send.");

       //call your web service here, or do whatever you wanted to do
   }
}

来自 JavaScript:

SendForm = function() {
   var name = $get("NameTextBox").value;
   var email = $get("EmailTextBox").value;
   var message = $get("MessageTextBox").value;

   PageMethods.SendForm(name, email, message, OnSucceeded, OnFailed);
}    
OnSucceeded = function() {
   $get("ContactFieldset").innerHTML = "<p>Thank you!</p>";
}    
OnFailed = function(error) {
   alert(error.get_message());
}

【讨论】:

  • 我已经尝试过了,但我收到了消息:“Microsoft JScript 运行时错误:'PageMethods' 未定义”... ContactUs 类是运行 js 的 c# 类 asp 或者它是服务类?
  • 好的。有用。我在 asp 页面的 scriptManager 中添加了 EnablePageMethods="true"。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2014-08-17
  • 2021-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多