How to display textarea's data in a table
I am using ASP.MVC 3. I have a view that has a textarea on it. I captures data in it, and when I want a new paragraph I wil press enter twice. After all my data is entered I save the text to the database.
In my details view I would display the data in 开发者_Python百科a like:
<tr>
<td valign="top"><label>Body:</label></td>
<td>@Model.Body</td>
</tr>
Now the text displays as 1 paragraph even though in my textarea (when I captured the data) it seemed liked paragraphs.
How would I get the data to display as paragraphs in my table like what I captured it in my textarea. I'm assuming that I have to search for carriage returns and replace them with break tags?
I'm assuming that I have to search for carriage returns and replace them with break tags?
Yes, your assumption is correct. You could use a custom HTML helper:
public static IHtmlString FormatBody(this HtmlHelper htmlHelper, string value)
{
if (string.IsNullOrEmpty(value))
{
return MvcHtmlString.Empty;
}
var lines = value.Split('\n'); // Might need to adapt
return htmlHelper.Raw(
string.Join("<br/>", lines.Select(line => htmlHelper.Encode(line)))
);
}
and then:
@Html.FormatBody(Model.Body)
UPDATE:
And here's an example of how this method could be unit tested:
[TestMethod]
public void FormatBody_should_split_lines_with_br_and_html_encode_them()
{
// arrange
var viewContext = new ViewContext();
var helper = new HtmlHelper(viewContext, MockRepository.GenerateStub<IViewDataContainer>());
var body = "line1\nline2\nline3<>\nline4";
// act
var actual = helper.FormatBody(body);
// assert
var expected = "line1<br/>line2<br/>line3<><br/>line4";
Assert.AreEqual(expected, actual.ToHtmlString());
}
精彩评论