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

前端 未结 11 597
逝去的感伤
逝去的感伤 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条回答
  •  执笔经年
    2020-12-14 16:04

    You should always encode user entered text when displaying it back in the view to ensure that it is safe.

    You could do as Cybernate suggested or could add it to a HtmlHelper extension method

    public static string EncodedMultiLineText(this HtmlHelper helper, string text) {
      if (String.IsNullOrEmpty(text)) {
        return String.Empty;
      }
      return Regex.Replace(helper.Encode(text), Environment.NewLine, "
    ") }

    So that it can be easily reused in you view

    <%= Html.EncodedMultiLineText(Model.Description) %>
    

提交回复
热议问题