[英]calling a c# function from javascript dosent work
I'm buildung a WebApplication in asp.net with c# and i have a problem to call ac# function from the JS. 我用c#在asp.net中构建了一个WebApplication,我有一个问题就是从JS调用ac#函数。
My code is like this: 我的代码是这样的:
in js: 在js中:
Function doStuff()
{
var service = new seatService.Service1();
service.DoWork(id, onSuccess, null, null);
}
and in the service page is: 并在服务页面中:
[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
}
}
The strange thing is that one of 20 times it actually works (with the same code) but most of the time it fails and I get the message: 奇怪的是它实际工作20次之一(使用相同的代码),但大部分时间它失败了,我收到了消息:
uncaught referenceEror - seatService is not defined. 未捕获的referenceEror - 未定义seatService。
and the status code is 500 Internal Server Error.
状态代码为500 Internal Server Error.
Since it sometime working and sometime doesn't - where is my problem? 因为它有时工作,有时不工作 - 我的问题在哪里?
You want to use PageMethods
for this. 您想要使用PageMethods
。 Here's some sample code to demonstrate: 以下是一些示例代码:
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
}
}
From JavaScript: 来自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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.