I have code that sends an email message to users on registration:
await UserManager.SendEmailAsync(2, "Confirm your account",
"Please confirm your account by clicking this link: <a href=\"www.cnn.com\">link</a>");
This works but I want to do something a lot more advanced and I have seen many templates out there. However all templates out there are at least 100 lines long and have newlines after every line. Here's an example of when I tried adding just one new line.
await UserManager.SendEmailAsync(2, "Confirm your account",
"Please confirm your account by clicking this link:
<a href=\"www.cnn.com\">link</a>");
As soon as I have a new line then I get a message saying I cannot include a new line in a constant.
Can anyone suggest another way that I could include do this?
There are three issues here. The first is that if you have a lot of text, you shouldn't be including that in the source code directly anyway. For small localizable pieces of text, you can use a resx/resources file - Visual Studio will present you with a grid so you can specify text for a particular resource name etc.
For lots of text, however, I'd strongly consider creating a .txt
file which you embed into your assembly, and read with Assembly.GetManifestResourceStream
. It's much easier to edit a text file than to manage large blocks of string literals.
The rest of the answer, however, addresses the question you actually asked, about string literals.
Second is getting a line break into the string, which can be done either by including it directly using escape sequences:
await UserManager.SendEmailAsync(2, "Confirm your account",
"Please confirm your account by clicking this link:\r\n<a href=\"www.cnn.com\">link</a>");
(Here \r\n
is a carriage return and line feed. Sometimes you may want just \r
or just \n
. It depends on the context.)
Or a verbatim string literal:
await UserManager.SendEmailAsync(2, "Confirm your account",
@"Please confirm your account by clicking this link:
<a href=""www.cnn.com"">link</a>");
Note that in a verbatim string literal, you need to escape double-quotes by doubling them, as a backslash is just a backslash.
But that will just give you a line break in your HTML. If you're trying to get a line break in the displayed text, you should use HTML. For example, you could use:
await UserManager.SendEmailAsync(2, "Confirm your account",
"Please confirm your account by clicking this link:<br /><a href=\"www.cnn.com\">link</a>");
... but I gather the <br>
tag is mostly out of favour - you should look at other ways of controlling the layout of your HTML. Just remember that a linebreak in the HTML itself is unlikely to be relevant in your page.
See more on this question at Stackoverflow