7

How do I add a newline after each item, in a textarea that's inside a Razor @foreach statement?

The code below displays everything on one line like...

12341524345634567654354487546765

When I want...

12341524

34563456

76543544

87546765

<textarea>
    @foreach (var item in ViewData.Model)
    {
                @item["ACCT_ID"]
    }
</textarea>
SharpC
  • 6,974
  • 4
  • 45
  • 40
GRU119
  • 1,028
  • 1
  • 14
  • 31

2 Answers2

5

You can add raw HTML with the HTML helper @Html.Raw(). In your case, something like this should work:

<textarea>
    @foreach (var item in ViewData.Model)
    {
        @item["ACCT_ID"]
        @Html.Raw("\n")
    }
</textarea>

This will insert a raw newline character (\n) after each item.

SharpC
  • 6,974
  • 4
  • 45
  • 40
Daniel Grim
  • 2,261
  • 19
  • 22
  • 2
    Thanks for the reply Dan. Unfortunately, when I added the '@Html.Raw("
    ") ' , it literally added the syntax
    in the output text area.
    – GRU119 Jun 03 '16 at 18:59
  • 1
    My bad, you should use `\n` instead of `
    ` inside a `textarea` tag. I've updated my answer.
    – Daniel Grim Jun 03 '16 at 19:02
  • 1
    That worked! I also just found you can use You could use @: to escape as well as . But I think I like your way better. Much appreciated. – GRU119 Jun 03 '16 at 19:11
1

In your controller:

Simply escape the newline, \n, character in your string.

message = "Violation of UNIQUE KEY constraint" + "\\n";
message += "Customer " + Customer.ToString() + "\\n";
message += "Invoice " + Invoice.ToString();

Viewbag.AlertMessage = message;

In your View:

@if (ViewBag.Alertmessage != null)
{
    <script type="text/javascript">
           alert("@ViewBag.Alertmessage");
        ViewBag.AlertMessage = "";
    </script>
}
WrqnHrd
  • 11
  • 2