Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a HTML text multiline using a C# bind in a blazor project?

I have a Blazor project with a ClientSide Razor Page. On that page I want to show a multiline text, for example:

Series not found
Error message

But the text is found in a C# string using a @bind.

I have tried using the normal \n to make a newline. It did pickup that it was command, but it placed a "space" in the text instead of making a new line.

I have also tried writing <br /> in the text, but then it just wrote that in the text.

My razor page:

<p>@resultString</p>

@code {
    string resultString = "Series not found \nError message";
}

With the input in the code snippet I would expect the following output:

Series not found
Error message

like image 778
Alex Kristensen Avatar asked Oct 21 '19 18:10

Alex Kristensen


People also ask

How do I make multiple lines of text in HTML?

The <textarea> tag defines a multi-line text input control. The <textarea> element is often used in a form, to collect user inputs like comments or reviews. A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier).

How do you make a multiline TextBox?

Step 1: Create a windows form. Step 2: Drag the TextBox control from the ToolBox and drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the TextBox control to set the Multiline property of the TextBox.

How do you show multiple lines of text?

The correct way to do things is using things made for the things you need. If you want a line break (enter), use <br> ; If you want to define a paragraph, use <p> . Show activity on this post. According to this, the <br> element is used to insert a line break without starting a new paragraph.


2 Answers

You can always go for the simple approach: split and loop

@foreach (var line in resultString.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
        <p>@line</p>
 }

@code {

    public string resultString  => "Series not found \nError message";
}
like image 74
Postlagerkarte Avatar answered Sep 28 '22 11:09

Postlagerkarte


I don't think it's a good idea to render the raw html tag because it is so dangerous most of the time.

As for your question, I would suggest you should add one line CSS code to display the line breaking:

<p style="white-space: pre-line" >@resultString</p>

@code {
    string resultString = "Series not found \nError message";
}

Demo

enter image description here

like image 20
itminus Avatar answered Sep 28 '22 11:09

itminus