无需刷新页面即可发送电子邮件

我有一个页面,底部有一个联系我们表格。

我想要实现的目标 – 从网站发送一封电子邮件而不发回邮件,重新加载所有页面并将客户移至页面顶部(联系我们表单位于底部)。

而不是 – 客户将按下发送按钮,然后将显示邮件发送的一些手势。

我知道如何使用常规方法发送邮件,我想要完成的是使用jquery.ajax从客户端发送它 – 这是该方案的最佳方式吗?

我做的是, 客户端

$('#btnSubmit').on('click', function () { var fullName = $('#txt_fullName').val(); var fromEmail = $('#txt_email').val(); var comments = $('#txtArea_message').val(); var fromPhone = $('#txt_phone').val(); var data = "{'name': '" + name + "', 'fromEmail': '" + fromEmail + "', 'comments': '" + comments + "', 'fromPhone': '" + fromPhone + "'}"; if (contactus == 0) { $.ajax({ type: "POST", url: "Default.aspx/sentMail", data: data, contentType: "application/json; charset=utf-8", dataType: "json" }) }else if (contactus == 1) return false; }) 

服务器端我有这个:

 tring sender_email = txt_email.Text; string sender_fullName = txt_fullName.Text; string sender_phone = txt_phone.Text; string sender_message = txtArea_message.Text; MailMessage MyMailMessage = new MailMessage(); MyMailMessage.From = new MailAddress("XXX@gmail.com", "Site"); MyMailMessage.To.Add("XXX@gmail.com"); MyMailMessage.Subject = "messge from site"; MyMailMessage.Body = "message"; MyMailMessage.IsBodyHtml = true; try { SmtpClient SMTPServer = new SmtpClient(); SMTPServer.Send(MyMailMessage); } catch (Exception ex) { } 

它不起作用 – 我不知道为什么(如何使用Google Chrome调试?)

http://jsfiddle.net/uptownapps/QBvZu/

在这个例子中,我的表单有id="contactForm" ,这是我将如何使用jQuery访问它。

  // We are looking to intercept the "submit" event on the form // whether that comes from a user clicking the "submit" button // or hitting "enter" on their keyboard while on a form element. $( document ).on('submit', '#contactForm', function( event ) { // We are going to handle the interaction with the server ourselves // so we want to prevent the browser from performing the default action event.preventDefault(); // serialize() on a from element will create the query string data // like you would typically see in a GET request // (ie "name=UptownApps&email=support@getuptownapps.com" etc.) var formData = $('#contactForm').serialize(); $.ajax({ // Send the request to the same place the form was originally going to url: $('#contactForm').attr('action'), // In this case I'm using POST. 'GET' is also acceptable. type: 'POST', // This callback function fires after successfully communicating // with the server success: function(data) { // data contains server's response $('#contactForm').slideUp(400); // Hide the form $('#successMessage').slideDown(400); // Show the success message }, // Error callback fires if there was an issue communicating with the server // Or a non-200 HTTP status is returned error: function(data) { // data contains server's response $('#errorMessage').slideDown(400); // Show the error message } }); }); 

在完成ajax调用后,请考虑使用jquery滚动到页面顶部。

 $.ajax({url: '/'}).done(function(data) {window.scrollTo(0,0);}); 

一般的答案是你可以使用AJAX实现这一点,因此你可以研究Microsoft ASP.NET AJAX。 然而,既然你似乎已经想到了这一点,但是已经走错了道路,这里有几个笔记。

你发布到Default.aspx/sentMail页面,我不确定IIS如何处理它,但据我所知,它会打开Default.aspx并忽略sentMail部分(它不会发送它一个POST参数sentMail因为它看起来像你期望的。如果你想使用这种方法,你需要发布到Default.aspx(或任何页面),但你需要设置$.ajax的参数data $.ajax如此处所示 (在页面中搜索POST)。然后,您需要从POST而不是控件获取变量,而不是您发布的服务器端代码。但是,这不是一种非常有效的方法事情的类型,所以我不会详细介绍。

更好的方法是使用SendEmail方法创建Web服务,并使用Microsoft ASP.NET AJAX 。 这将更容易,更快速,更清洁。

我还想补充两点。

  1. 您在客户端编写了使用$('#btnSubmit') 。 如果您正在使用控制(按钮)的预测命名,那可以,但这不是默认行为,所以如果您不知道,您应该为客户端使用$('#<%= btnSubmit.ClientID %>')控件的id。
  2. 如果你打开一个网络服务来发送电子邮件,任何人都可以随时打电话给他们,他们想要多少次让你接受各种攻击。 我建议您实现某种检查,也许在您存储在会话中的页面上呈现变量(可能是GUID),并使Web服务方法在发送邮件之前检查发送的参数是否实际在会话中。 请注意,您需要添加EnableSession=true属性,如此处所述,以便能够从Web方法访问会话。

你的客户端javascript似乎很好,但如果你在C#上将属性映射到这样的对象会更好:

 public class Mail { public string FullName {get; set;} public string FromEmail {get; set;} public string ToEmail{get; set;} public string Comments {get; set;} public string FromPhone {get; set;} } 

并将您的jquery更改为此(将Class Mail的属性映射到您的View Input Content):

  $('#btnSubmit').on('click', function () { var fullName = $('#txt_fullName').val(); var fromEmail = $('#txt_email').val(); var comments = $('#txtArea_message').val(); var fromPhone = $('#txt_phone').val(); var data = { FullName: fullname, FromEmail: fromEmail, Comments: comments, FromPhone: fromPhone, }; if (contactus == 0) { $.ajax({ type: "POST", url: "Default.aspx/sentMail", data: data, contentType: "application/json; charset=utf-8", dataType: "json" }) }else if (contactus == 1) return false; }); 

并且您在服务器端的function必须是web方法,如下所示:

 [WebMethod] public string SentMail(Mail mail) { //use properties of Class Mail to send MailMessage MyMailMessage = new MailMessage(); MyMailMessage.From = new MailAddress("XXX@gmail.com", "Site"); MyMailMessage.To.Add(mail.To); MyMailMessage.Subject = mail.Comments; MyMailMessage.Body = mail.Comments; MyMailMessage.IsBodyHtml = true; try { SmtpClient SMTPServer = new SmtpClient(); SMTPServer.Send(MyMailMessage); } catch (Exception ex) { } return ""; }