Maintain whitespace when displaying text from database

拈花ヽ惹草 提交于 2019-12-21 20:36:30

问题


I'm putting up a table that displays values from a table. One of the fields comes from a textarea input.

If I use this method then whitespace is maintained:

@Html.TextAreaFor(model => model.goalDescr, new { cols="90", rows="3", @readonly = "true"})

--example:

hey

there

--end example

However, I don't like that view so much as it still looks like a form field. I tried to use displayfor but the white space is removed and all text is one one line.

@Html.DisplayFor(model => model.goalDescr)

--example:

hey there

--end example

Is there a way to display text in my view in, outside of a form element, and maintain white space?


回答1:


wrap your DB content into a pre tag

<pre>
 All whitespaces      and linebreaks
are preserved

</pre>



回答2:


As Steve B's answer says, you can use <pre> to maintain whitespace.

If however you don't like the auto-formatting <pre> does and want to keep your inherited styling simply use a <span> or <div> with the style="white-space:pre-wrap;" attribute. I find this to be a more elegant solution.

Live demo




回答3:


You could write a custom helper which will replace new lines (\r\n) with <br/> tags.

public static class HtmlExtensions
{
    public static IHtmlString FormatValue(this HtmlHelper html, string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return MvcHtmlString.Empty;
        }
        value = string.Join(
            "<br/>", 
            value.Split(new[] { Environment.NewLine }, StringSplitOptions.None)
                 .Select(x => html.Encode(x))
        );
        return MvcHtmlString.Create(value);
    }
}

and then:

@Html.FormatValue(Model.goalDescr)

or wrap in a <pre> tag to preserve new lines:

<pre>
    @Html.DisplayFor(x => x.goalDescr)
</pre>



回答4:


When you use DisplayFor, my guess is that it's rendering input type="text" instead of textarea which is the reason why it's displaying it in one line.

You can decorate you model with [DataType(DataType.MultilineText)] like this:

[DataType(DataType.MultilineText)]
public string goalDescr { get; set; }


来源:https://stackoverflow.com/questions/7353489/maintain-whitespace-when-displaying-text-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!