我正在尝试在我的控制器中编写代码,该代码在运行时将创建一堆变量,然后使用具有占位符以包含变量的模板发送电子邮件。但是,它将用户帐户中的信息分配给变量,如果用户尚未填写该信息,它将崩溃。作为一种解决方法,我在 if 语句中声明了它们,以确保它们首先不为空。但是现在当我尝试将它们传递给电子邮件模板时,它告诉我该变量不存在。如果我删除 if 语句,它会再次起作用。任何想法为什么?
代码如下...
if (UserContext != null && UserContext.Account != null)
{
if (UserContext.UserName != null)
{ string UserName = string.Format(UserContext.UserName); }
if (UserContext.EmailAddress != null)
{ string EmailAddress = string.Format(UserContext.EmailAddress); }
if (UserContext.Account.PrimaryContactFirstName != null)
{ string FirstName = string.Format(UserContext.Account.PrimaryContactFirstName); }
if (UserContext.Account.PrimaryContactLastName != null)
{ string LastName = string.Format(UserContext.Account.PrimaryContactLastName); }
if (UserContext.Account.PrimaryContactPhoneNumber != null)
{ string PhoneNumber = string.Format(UserContext.Account.PrimaryContactPhoneNumber); }
if (UserContext.Account.HeadquartersAddressLine1 != null)
{
string AddressLine1 = string.Format(UserContext.Account.HeadquartersAddressLine1);
if (UserContext.Account.HeadquartersAddressLine2 != null)
{ string AddressLine2 = string.Format(UserContext.Account.HeadquartersAddressLine2); }
}
if (UserContext.Account.HeadquartersCity != null)
{ string City = string.Format(UserContext.Account.HeadquartersCity); }
if (UserContext.Account.HeadquartersState != null)
{ string State = string.Format(UserContext.Account.HeadquartersState); }
if (UserContext.Account.HeadquartersZip != null)
{ string ZipCode = string.Format(UserContext.Account.HeadquartersZip); }
if (UserContext.Account.Name != null)
{ string Name = string.Format(UserContext.Account.Name); }
string body = string.Format(Resources.ContactUsLoggedInEmailTemplate, model.FirstName, model.LastName, model.PhoneNumber, model.Email, model.ReasonForContact, model.Message, UserName, EmailAddress, FirstName, LastName, PhoneNumber, AddressLine1, AddressLine2, City, State, ZipCode, Name);
string subject = string.Format("Web Submit: {0}", model.ReasonForContact);
EmailHelper.SendEmail("support@website.com", subject, body, true);
}
if (UserContext == null)
{
string body = string.Format(Resources.ContactUsEmailTemplate, model.FirstName, model.LastName, model.PhoneNumber, model.Email, model.ReasonForContact, model.Message);
string subject = string.Format("Web Submit: {0}", model.ReasonForContact);
EmailHelper.SendEmail("support@website.com", subject, body, true);
}
return RedirectToAction("ContactConfirmation");