Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have New Line in Blazor

I'm trying to create a newline, and having already looked on other forums, some are using '\n', '\r' or Environment.NewLine but personally nothing works. I give you the code and the result :

1:

string n1 = SomeText;
string n2 = AnotherText;
string beforeStr = n1 + Environment.NewLine + n2;

2:

string n1 = SomeText;
string n2 = AnotherText;
string beforeStr = n1 + '\r' + n2;

3:

string n1 = SomeText;
string n2 = AnotherText;
string beforeStr = n1 + '\n' + n2;

always same result :

SomeText AnotherText
like image 273
SoyNeko Avatar asked Nov 18 '25 19:11

SoyNeko


1 Answers

The MarkupString solution will swallow/interpret all non-escaped html characters. This can lead to a XSS attack with dynamic user input strings.
The way to go here is to html-escape first and then replace all line breaks with <br />

@using System.Web
@using System.Text.RegularExpressions;

<div>
  @((MarkupString)Regex.Replace(
    HttpUtility.HtmlEncode(@multilineString), "\r?\n|\r", "<br />"))
</div>

The regex \r?\n|\r will replace \r (old Mac), \r\n (Windows) and \n (Unix)

This can also be implemented as a Component.

MultilineString.razor

@using System.Web
@using System.Text.RegularExpressions;

@((MarkupString)Regex.Replace(HttpUtility.HtmlEncode(@Value), "\r?\n|\r", "<br />"))

@code {
    [Parameter]
    public string Value { get; set; } = default!;
}

Now it's easier to use with <MultilineString Value=@yourInput />

like image 165
5andr0 Avatar answered Nov 20 '25 10:11

5andr0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!