andrewdavey / postal

Email sending for asp.net mvc using the view engine system to render emails.
http://aboutcode.net/postal
MIT License
536 stars 168 forks source link

Separate service and viewmodel #107

Open migig opened 9 years ago

migig commented 9 years ago

We have a common base class for all viewmodels. So a viewmodel cannot inherit from that base class and from Postal.Email.

Seems others have this problem as well: see here, and here.

This pull request allows you to do this:

var viewName  = "~/Views/Foo/Index.cshtml";
var viewModel = new FooViewModel();
var service   = new EmailService();
service.Send(viewName, viewModel);

By adding overloads as I did, it also means that it's backwards compatible for those who want to carry on using it as is.

What do you think?

migig commented 9 years ago

I've since discovered another way to do this:

// create view model
var viewModel = new EmailViewModel();  // derives from a base class used by all view models
// populate the view model, etc.

// prepare the razor view template
var viewName = "~/Views/Emails/Template1.cshtml";
var email = new Postal.Email(viewName);
email.ViewData = new ViewDataDictionary(viewmodel);  // the trick that makes everything work

// render the template, and send the email
var service = new Postal.EmailService();
service.Send(email);

This works, but nonetheless, it would be better to have it in built into Postal.

At the very least, if you decide to reject the change, please add this approach to the documentation, so others can benefit? I'm also worried that the ViewData signature may change in the future, but if you document it then you won't be able to! ;)

hanc2006 commented 9 years ago

Your trick works. I think it's better to add a new overloads for an easier use but not inside the email service class. The email service has to deal only to send the email correctly. The build of the email (viewmodel, data, sender, ...) must be done elsewhere.