简体   繁体   English

使用JavaScript在HTML页面中调用C#Web服务功能

[英]Call C# webservice function in HTML page using javascript

How do I call a C# webservice function in HTML page using Javascript? 如何使用Javascript在HTML页面中调用C#Web服务函数? I have been trying with the following code, but my Javascript function is not even communicating to the webservice. 我一直在尝试以下代码,但是我的Javascript函数甚至没有与Web服务通信。

Javascript Function: 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 C#Web服务

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";
    }
}

This is how i do it: 这是我的方法:

Add a href to the page and some js at the bottom: 在页面上添加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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM