public async Task<ActionResult> Rsvp(RsvpViewModel model) { if (!string.IsNullOrWhiteSpace(model.Website) || model.CaptchaPass == null || model.CaptchaPass != "KALASHIAN_NOT_ROBOT") { return Json(new { status = 0, error = "Only humans can submit this form." }); } using (NickBeckyWedding db = new NickBeckyWedding()) using (DbContextTransaction dbTrans = db.Database.BeginTransaction()) { RSVP rsvp = new RSVP { ArrivalDate = model.ArrivalDate, PrimaryEmail = model.EmailAddress, Attending = model.Attending }; db.RSVPs.Add(rsvp); try { await db.SaveChangesAsync(); } catch (Exception ex) { dbTrans.Rollback(); return Json(new { status = 0, error = ex.Message }); } RSVPAttendee primeAttendee = new RSVPAttendee { EmailAddress = model.EmailAddress, Name = model.Name, RSVP_ID = rsvp.ID }; db.RSVPAttendees.Add(primeAttendee); foreach (RSVPAttendee dbAttendee in model.Attendees.Where(attendee => attendee.EmailAddress != null).Select(attendee => new RSVPAttendee { EmailAddress = attendee.EmailAddress, Name = attendee.Name, RSVP_ID = rsvp.ID })) { db.RSVPAttendees.Add(dbAttendee); } try { await db.SaveChangesAsync(); dbTrans.Commit(); } catch (Exception ex) { dbTrans.Rollback(); return Json(new { status = 0, error = ex.Message }); } await SendRsvpEmailAsync(model); } return Json(new { status = 1 }); }
//public async Task<ActionResult> TestEmail() //{ // RsvpViewModel model = new RsvpViewModel { EmailAddress = "*****@*****.**", Name = "Connor Grady", Attending = false, ArrivalDate = new DateTime(2016, 11, 11), OtherAttendees = false, Attendees = new List<RsvpAttendeeViewModel> { new RsvpAttendeeViewModel { Name = "Robin Grady", EmailAddress = "*****@*****.**" } } }; // Dictionary<string, string> recipients = new Dictionary<string, string> // { // {"Connor Grady", "*****@*****.**"} // }; // await SendRsvpEmailAsync(recipients, model); // return RedirectToAction("Index", "Home"); //} private async Task SendRsvpEmailAsync(RsvpViewModel model) { SendGridMessage message = new SendGridMessage { From = new MailAddress("*****@*****.**", "Becky & Nick"), Subject = "RSVP Confirmation | Becky & Nick's Wedding", Html = this.RenderPartialViewToString("RSVPEmail", model) }; message.AddTo($"{model.Name} <{model.EmailAddress}>"); SendGrid.Web transportWeb = new SendGrid.Web(ConfigurationManager.AppSettings["sendgrid:APIKey"]); await transportWeb.DeliverAsync(message); }