Search code examples
c#asp.netasp.net-mvcrazorpostal

How to make CC field optional using postal asp.net


I am using postal to send email using postal service in my asp.net mvc application now the issue is I have to send CC email in specific cases only and I have to make this field optional but I am not been to achieve this so far. Following is my code for this:

View file:

@model OAC.Helpers.EmailHelper

To: @Model.To
Form: @Model.From
CC: @Model.CC
Subject: @Model.Subject


Hello,

@Model.Body

@Model.Link

public class EmailHelper : Email
{
    public string To { get; set; }
    public string CC { get; set; }
    public string Body { get; set; }
    public string Subject { get; set; }
    public string From { get; set; }
    public string Link { get; set; }
    public static void SendEmailNotification(string emailAddress, string body, string link, string subject, string from = "OAC Support", string CC = null)
    {
        // Prepare Postal classes to work outside of ASP.NET request
        var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
        var engines = new ViewEngineCollection();
        engines.Add(new FileSystemRazorViewEngine(viewsPath));
        var emailService = new EmailService(engines);
        var email = new EmailHelper
        {
            To = emailAddress,
            CC = CC, 
            Body = body,
            Subject = subject,
            From = from,
            Link = link
        };
        emailService.Send(email);
    }
}

Now I want to make the CC field in view optional so that when CC is "null" the view ignores the "@Model.CC" field. Something as following:

@model OAC.Helpers.EmailHelper

To: @Model.To
Form: @Model.From
if(Model.CC != null)
{
 CC: @Model.CC
}
Subject: @Model.Subject


Hello,

@Model.Body

@Model.Link

Kindly Help! Thank you.


Solution

  • You were very close, just change the View. Need "@:" before the CC: @Model.Cc

    e.g.

    @if (Model.Cc != null)
    {
        @:CC: @Model.Cc
    }