'How to render and preserve <br> tags as line breaks using @Html.TextAreaFor

I'm migrating an ASP Classic app to ASP.Net MVC 5. The legacy data contains <BR> tags in the text. In the old application (still in use) the tags are rendered as line breaks. The data was created and displayed using plain html <textarea> tags. A list of Mill Roll numbers, for example, is entered in a single field on multiple lines. How can I preserve this behavior in MVC? I've tried:

@Html.TextAreaFor(model => model.MillRoll, new { @class = "form-control" })

The result is an input control displaying a single line of multiple Mill Rolls with the <BR> tag between each roll number instead of displaying multiple lines. I'm not interested in breaking the data off into another table. The new app will need to behave like the old allowing entry and saving of multiple lines in a single input control. I'd like to make the transition to the MVC app simple for both myself and users.



Solution 1:[1]

You can convert data on the fly using properties for example.
Replace "< br >" with "\r\n" and back (You can also use System.Environment.NewLine instead of "\r\n").
So when you get legacy data, replace "< br > with "\r\n" it should then show ok it textarea. If you need to save changes in legacy format with < br > just replace "\r\n" with < br > and save it.

public string myLegacyDataString;
public string MyDataString{
    get {return myLegacyDataString.Replace("< br >","\r\n");}
    set {myLegacyDataString = value.Replace("\r\n", "< br >");}
}

or with NewLine:

public string myLegacyDataString;
public string MyDataString{
    get {return myLegacyDataString.Replace("< br >",System.Environment.NewLine);}
    set {myLegacyDataString = value.Replace(System.Environment.NewLine, "< br >");}
}

Solution 2:[2]

Use Html.Raw to preserve the BR tags

@Html.Raw("<br>")

The idea came from here: Output Raw String in ASP.NET MVC Razor

I've been working on a project that involves re-writing old vbscript asp.net code as well. The old code would often put BR tags into strings to display on the page. But razor would dutifully display it as &lt;br&gt;. So it would show up on my page as a <BR> instead of a line break.

I don't have access to your code (you probably have moved on from trying to solve this, by now) but I imagine if you put something like:

@Html.TextAreaFor(model => @Html.Raw(model.MillRoll), new { @class = "form-control" })

it would give you what you want.

(You many need to not include the @ symbol by Html.Raw. I can never seem to understand exactly when it is needed with Razor.)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmitri Usanov
Solution 2 Joe