I have contact form that logs a serialized version of a contact model to a database and sends an email with the form data. Between the two actions, it takes up to 2 seconds to complete. Although not a lot of time, it is enough to annoy impatient users.
Contact Controller:
public class ContactController : Controller
{
// GET: Contact
public ActionResult Index()
{
return View();
}
// Post: /Contact/
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Models.ContactModel contact)
{
if (ModelState.IsValid)
{
XmlSerializer xmlSerializer = new XmlSerializer(contact.GetType());
using (StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, contact);
Log.Create("email", textWriter.ToString());
}
Smtp.sendMail(sendTo, contact.Email, contact.Name, subject, contact.Comment,
ipAddress, senderEmail, contact.Phone, sendBcc);
// using RedirectToRoute instead of RedirectToAction so that /contact is used.
return RedirectToRoute("Default", new { action = "contactsucess", controller = "contact" });
}
// Return Form if not valid
return View(contact);
}
// GET: /Contact/ContactSucess
public ActionResult ContactSucess()
{
ViewBag.IsContactPage = true;
return View();
}
}
What is the best approach to make serializing, logging and STMP logic asynchronous to the controller returning the success/thank you page. Basically my goal is to prevent those calls from blocking the overall progress so that the form completes faster.