我正在使用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 - 未定义seatService。
,状态代码为500 Internal Server Error.
因为它有时工作而有时没有 - 我的问题在哪里?
答案 0 :(得分:2)
您想使用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());
}