We have a requirement that when saving a specific type of string to the database it needs to save newline characters as a string (“\n”) not the character literal (‘\n’). It should have been straight forward but I found myself spinning in circles and decided to make a note on what the final code looked like.
CSHTML View:
@Html.TextArea("Message", Model.Message, new { maxlength = 5000 })
Saving to DB:
item.Message = model.Message.Replace("\r\n","\\n");
Pulling from DB:
if (item != null) { Message = item.Message.ToStringOrEmpty().Replace("\\n", "\r\n"); } if (Message.IsNullOrEmpty()) Message = "Message goes here.\r\n\r\nSincerely,";