mirosz
mirosz

Reputation: 417

MVC - Passing Model from Controller to a Class

I want to send an e-mail from my controller calling a static function located in a class EmailHelper. As a parameter I want to use my model so I can call it just like that:

EmailHelper.SendEmail(MyModel model)

I just need to call that function in many places passing different models. How to achieve that?

Upvotes: 0

Views: 459

Answers (2)

invernomuto
invernomuto

Reputation: 10211

You should use an interface to your model (for example IEmailModel)

public interface IEmailModel{
  string propertyUsedByHelper {get;set;}

}
public class MyModel: IEmailModel{
  public string propertyUsedByHelper {get;set;}

}

then your helper will do the trick

EmailHelper.SendEmail(IEmailModel model)

public static class EmailHelper {
  public void SendEmail(IEmailModel model)
  {
    IEmailModel m = model;
    string prop = m.propertyUsedByHelper;
  }
}

BTW your is a typical cross concern need, so the best method to manage this need is aspect oriented programming, take a look to interception in PostSharp or also Castle dynamic proxy

Upvotes: 1

LazyOfT
LazyOfT

Reputation: 1438

I would recommend to have your specific model for email messages, and convert from your specific model inside the controller to the model used for email messages. This way the function can be reused regardless of both the model being used and the project.

One way to create an email model from your specific model and keep the code readable could be to use an Extension method class, providing conversion methods towards the email message

public static class EmailConverters
{
    public static EmailModel ToEmail(this MyModel model)
    {
        // Create a new EmailModel based on MyModel fields and return that
    }
}

this way on your controller you can write something like:

EmailHelper.SendEmail(model.ToEmail())

There are also other ways for doing this, specifically by using libraries such as AutoMapper and similar, but for an email message I would say they could be overkill.

Upvotes: 1

Related Questions