在View上按钮运行方法(ASP.NET MVC)

时间:2017-04-05 09:15:36

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我在发送电子邮件的后端上有Action Result

这是代码

public ActionResult SendEmail(SmartSolutions.Models.InvitationMail _objModelMail)
{
    if (ModelState.IsValid)
    {
        var emailList = db.InvitationMails.Select(model => model.To);
        var emailList2 = db.InvitationMails.Select(model => model.Link);
        var link2 = emailList2.FirstOrDefault();
        var emails = String.Join(",", emailList);
        MailMessage mail = new MailMessage();
        mail.To.Add(emails);
        mail.From = new MailAddress(_objModelMail.From = "suhomlin.eugene93@gmail.com");
        mail.Subject = _objModelMail.Subject = "Видео интервью";

        string Body = _objModelMail.Body = "Предлагаем пройти интервью" + link2;

        mail.Body = Body;
        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new System.Net.NetworkCredential
        ("***************", "**********");// Enter seders User name and password
        smtp.EnableSsl = true;
        smtp.Send(mail);
        return View("SendEmail", _objModelMail as IEnumerable<InvitationMail>);
    }
    else
    {
        return View();
    }
}

它很棒。 Afteк5秒后重定向回来。

我需要这个方法不在ActionResult I按钮中运行。

逻辑将是相同的,我点击按钮它会向表格中的所有人发送电子邮件。

我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

简单!您应该使用ajax请求调用此方法。

$.ajax({
    url: '/ControlllerName/SendEmail',
    dataType: "json",
    type: "GET",
    contentType: 'application/json; charset=utf-8',
    async: false,
    processData: false,
    cache: false,
    delay: 15,
    success: function (result) {
                    alert("Email Forworded")                    
    },
    error: function (xhr) {
        alert('error');
    }
});

并在SendEmail方法

中初始化它
Public JsonResult SendEmail ()
{
  SmartSolutions.Models.InvitationMail _objModelMail = new SmartSolutions.Models.InvitationMail();
 // here your code goes
}
希望有所帮助!