ASP.NET和AJAX文件上传

时间:2016-01-28 15:33:28

标签: c# jquery html asp.net ajax

我正在尝试创建一个解决方案,通过电子邮件向您发送一个人的信息。信息很容易处理,因为它是字符串但我无法弄清楚如何上传文件并提供给aspx以便发送带附件的邮件。我没有在上面的代码中包含我的尝试,因为他们只是保持崩溃程序。这是我的代码:

HTMLPage.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script src="Scripts/jquery-1.12.0.js" type="text/javascript"
            charset="utf-8"></script>
    <script src="Scripts/functions.js" type="text/javascript"
            charset="utf-8"></script>
    <form id="validate-form" method="post">
        <p>First Name: </p>
        <input type="text" id="name" />
        <p>Last Name:</p>
        <input type="text" id="lname" />
        <p>E-mail: </p>
        <input type="text" id="mail" />
        <p>CV: </p>
        <input type="file" id="CV" />
    </form>
    <button id="button" on""></button>
</body>
</html>

functions.js

$(function () {
    $('#button').click(function (e) {
        e.preventDefault();
        var name = document.getElementById("name").value;
        var lastName = document.getElementById("lname").value;
        var mail = document.getElementById("mail").value;
        var data = new FormData();
        $.ajax({
                    type: "POST",
                    url: '/AjaxHandler.aspx/Handle',
                    data: "{name:'" + name + "', lastName:'" + lastName + "', Mail:'" + mail + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: alert("Gönderildi")

                });

    }
)});

AjaxHandler.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.IO;
using System.Configuration;
using System.Net.Configuration;
using System.Web.Configuration;
using System.Web.Services;

public partial class AjaxHandler : Page
{
    [WebMethod]
    public static void Handle(string name, string lastName,string Mail)
    {
        try
        {
            SmtpSection cfg = NetSectionGroup.GetSectionGroup(WebConfigurationManager.OpenWebConfiguration("~/web.config")).MailSettings.Smtp;
            MailMessage mail = new MailMessage();
            mail.To.Add("mail@address.com");
            mail.Body = ("Name: " + name + " Last Name: " + lastName + " Email Adress: " + Mail);

            SmtpClient smtpClient = new SmtpClient(cfg.Network.Host, 587);
            smtpClient.EnableSsl = true;
            smtpClient.Send(mail);
        }
        catch
        {
        }
    }
}

0 个答案:

没有答案