1

I have a TextArea where a user can write some text. When i try to show the text with LabelFor, i get an "illegal characters" error, because it the string has "\r\n" for every new line.

I've tried to use this solution:

Show new lines from text area in ASP.NET MVC

and

     if (q.help_text != null)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            System.IO.StringReader sr = new System.IO.StringReader(q.help_text);

            string tmpS = null;
            do
            {
                tmpS = sr.ReadLine();
                if (tmpS != null)
                {
                    sb.Append(tmpS);
                    sb.Append("<br />");
                }
            } while (tmpS != null);
            var convertedString = sb.ToString();
            qvm.HelpText = convertedString;
        }
        else
            qvm.HelpText = q.help_text;

Instead of making new lines, LabelFor outputs the br code as well. How can i solve this?

EDIT

The solution was to do it this way:

@Html.Raw("

"+question.HelpText+"

Community
  • 1
  • 1
Nanek
  • 115
  • 2
  • 9
  • Please be aware with Cross Site scripting issue in case you choose to use the answer you have added – Ankur Aug 11 '11 at 16:13

2 Answers2

3

This is because LabelFor is HTML encoding the text . This is done to avoid cross site scripting issues. What you can do is use pre tag to render the text area string as it is (with \r\n)

Ankur
  • 33,367
  • 2
  • 46
  • 72
  • Can you provide an example please – Nanek Aug 11 '11 at 12:45
  • 1
    Something like `@Html.Raw("
    " + help_text + "
    ")` . NOTE: You don't need to replace \r\n with
    in `help_text`
    – Ankur Aug 11 '11 at 12:47
  • I just tested this, it does show new lines. BUT it stretches my so it doesnt fit the screen. Also, the text formatting is not the same as the rest :/ – Nanek Aug 11 '11 at 12:55
0

Use this syntax for LabelFor

@Html.Raw(Html.LabelFor(x => x.Name))
Govind Malviya
  • 13,627
  • 17
  • 68
  • 94
  • Html.LabelFor returns MvcHtmlString, Html.Raw takes string as parameter. If i do: @Html.Raw(@Html.LabelFor(y=>question.HelpText, question.HelpText).ToString()) it returns the same result as LabelFor – Nanek Aug 11 '11 at 12:42
  • 1
    I just tested your method with my code and it outputs the same result as LabelFor, it doesnt show new lines :/ – Nanek Aug 11 '11 at 12:54
  • @Html.Raw("

    "+question.HelpText+"

    – Nanek Aug 11 '11 at 13:40