如何使用Javascript在HTML页面中调用C#webservice函数?我一直在尝试使用以下代码,但我的Javascript函数甚至没有与Web服务进行通信。
Javascript功能:
<script language="JavaScript" type="text/javascript">
var iCallID;
function getEmail()
{
iCallID=document.getElementById("email").value;
service.useService("http://localhost:1551/MyWebSite/MyWebService.asmx?wsdl", "GetDateTimeService");
alert(iCallID);
service.GetDateTimeService.callService("sendEmail",iCallID);
alert(event.result.value);
}
</script>
C#Webservices
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net.Mail;
using System.Net;
/// <summary>
/// Summary description for MyWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class MyWebService : System.Web.Services.WebService
{
public MyWebService()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string sendEmail(string EmailID)
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.Credentials = new NetworkCredential("some-email@gmail.com", "password");
client.EnableSsl = true;
MailMessage mailmsg = new MailMessage();
mailmsg.From = new MailAddress(EmailID);
mailmsg.To.Add("some-email@gmail.com");
mailmsg.Subject = "test";
mailmsg.Body = "test mail";
client.Send(mailmsg);
return "Email Sent Successfully";
}
}
答案 0 :(得分:0)
我就是这样做的:
在页面中添加一个href,在底部添加一些js:
<a href="javascript:SendEmailJs()">Send mail!</a>
//Other logic
<script type="text/javascript>
function SendEmailJs(){
var url = '@(Url.Action("SendEmail"))';
var emailId = document.getElementById("email").value;
url += "/?EmailID=" + emailId;
$.get(url, function(data){
alert(data.tostring);
}
}
</script>