Adding new line within a textarea that's using asp.net razor markup
Asked Answered
P

2

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>
Piddle answered 3/6, 2016 at 18:17 Comment(0)
V
6

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.

Vedic answered 3/6, 2016 at 18:42 Comment(3)
Thanks for the reply Dan. Unfortunately, when I added the '@Html.Raw("<br />") ' , it literally added the syntax <br /> in the output text area.Piddle
My bad, you should use \n instead of <br /> inside a textarea tag. I've updated my answer.Vedic
That worked! I also just found you can use You could use @: to escape as well as <text> . But I think I like your way better. Much appreciated.Piddle
T
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>
}
Tawanda answered 23/4, 2018 at 21:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.