I've currently implemented Postal and I'm using that to send emails on my MVC application. The problem I'm having is that I want to retrieve an email address from my database, instead of hard-coding the address I want to send the email to.
So to give a bit of context on where I'd like to implement this. After I create my Order, I want to send an email address to the Hospital that is linked to that order.
This is what I have tried, but it throws an exception on this line email.To = order.Hospital.Email;
- It does work if I hard code the email address like, for example , email.To = "hospital@hospital.com".
An exception of type 'System.NullReferenceException' occurred in HealthHabitat.dll but was not handled in user code
I've included it in my Create POST method
so that it triggers once the model has been saved.
The email address is saved as a string in my Hospital Model.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "OrderID,HospitalID,StaffID,Date,Time,Expected_Date")] Order order)
{
if (ModelState.IsValid)
{
order.StaffID = 5;
db.Orders.Add(order);
db.SaveChanges();
dynamic email = new Email("Example");
email.To = order.Hospital.Email; // this is where you set the email you are sending to.
email.Send();
Success(string.Format("<i class='fa fa-plus-circle'></i> Please Add your Items!", order.OrderID), true);
return RedirectToAction("Details", new { id = order.OrderID });
}
ViewBag.HospitalID = new SelectList(db.Hospitals, "HospitalID", "Name", order.HospitalID);
Danger("<i class='fa fa-warning'></i> Error!", true);
return View(order);
}
Does any one have a solution to this? I'll greatly appreciate it and thanks in advance!
If any additional information is needed, please let me know and I'll add it to the question.
Hospital Model:
public class Hospital
{
public int HospitalID { get; set; }
public string Name { get; set; }
public string Province { get; set; }
public string Email { get; set; }
public string Phone_Number { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
}
You could do something like this:
order.StaffID = 5;
db.Orders.Add(order);
db.SaveChanges();
//select hospital from database.
Hospital hospital = db.Hospitals.First(h => h.HospitalId == order.HospitalId);
dynamic email = new Email("Example");
email.To = hospital.Email; // this is where you set the email you are sending to.
email.Send();