asp.net mvc convert \n new line to html breaks

前端 未结 11 594
逝去的感伤
逝去的感伤 2020-12-14 15:10

I have a textarea in mvc. When data is entered into that and I\'m displaying it back to the user, how do I show the line breaks?

I display like this:

相关标签:
11条回答
  • This works for me -

    <%= HttpUtility.HtmlDecode(Html.ActionLink("AOT <br/> Claim #", "actionName" ))%>

    0 讨论(0)
  • 2020-12-14 15:56

    It doesn't look like you're trying to HTML Encode so a regular replace should work fine.

    <%= Model.Description.Replace(Environment.NewLine, "<br />")%>
    
    0 讨论(0)
  • 2020-12-14 15:57

    For a slightly different (and, IMHO, better and safer) way of solving the problem, see this answer to a similar question.

    Basically, instead of going through the trouble of converting all new line characters to <br> elements, it is as simple as applying the following CSS to the element where you are showing the inputted text:

    white-space: pre-line
    
    0 讨论(0)
  • 2020-12-14 15:59

    Try something like this:

    <%=
    Regex.Replace(
                  Html.Encode(Model.Description), 
                  Environment.NewLine, 
                  "<br/>", 
                  RegexOptions.IgnoreCase||RegexOptions.Multiline
                 )
    %>
    
    0 讨论(0)
  • 2020-12-14 16:00

    For Asp.net mvc razor,i used Html.Encode for blocking xss attacks

    @Html.Raw(Html.Encode(Model.Description).Replace(Environment.NewLine, "<br />"))
    
    0 讨论(0)
  • 2020-12-14 16:00

    Maybe it's the answer: How do you handle line breaks in HTML Encoded MVC view?

    or

    you can try:

    Model.Description.Replace(Environment.NewLine, "<br/>");
    
    0 讨论(0)
提交回复
热议问题