MVC C# 网站应用程序中使用的 textarea 中的换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9844050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 10:52:03  来源:igfitidea点击:

line breaks in textarea used in a MVC C# website app

c#asp.net-mvctextarealine-breaks

提问by Harry

I'm using ASP.net MVC C# in Visual Studio Web Dev. I have a couple of textareas which are populated with data and then updated to a database record.

我在 Visual Studio Web Dev 中使用 ASP.net MVC C#。我有几个 textarea 填充了数据,然后更新到数据库记录。

Is it possible to have line breaks saved when a record is updated to the database? I currently view the data on the homepage, but at the moment if someone writes couple of paragraphs (including line breaks) the formatting will be lost.

当记录更新到数据库时,是否可以保存换行符?我目前在主页上查看数据,但目前如果有人写了几段(包括换行符),格式将丢失。

If this isn't possible no problem, but just wanted to ask if it is. Thanks.

如果这是不可能的没问题,但只是想问问它是否是。谢谢。

The code on the View page looks like this:

查看页面上的代码如下所示:

<div class="editor-field">
        @Html.TextAreaFor(model => model.para1, new { cols = 75, @rows = 5 })
        @Html.ValidationMessageFor(model => model.para1)
</div>

I then have a button that submits the form.

然后我有一个提交表单的按钮。

The Controller code that handles the submission looks like this:

处理提交的控制器代码如下所示:

[HttpPost]
    public ActionResult Update(Data data)
    {
        if (ModelState.IsValid)
        {
            data.ID = 1; //EF need to know which row to update in the database.
            db.Entry(data).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index", "Home");
        }
        return View(data);
    }

and the Model code for the database looks like this:

数据库的模型代码如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;

namespace DFAccountancy.Models
{
    public class Data
    {
        [DataType(DataType.MultilineText)]
        public int ID { get; set; }
        public string para1 { get; set; }
        public string para2 { get; set; }
    }

    public class DataDBContext : DbContext
    {
        public DbSet<Data> Data { get; set; }
    }
}

===========================================

============================================

the Homepage code

主页代码

@model IEnumerable<DFAccountancy.Models.Data>

@{
    ViewBag.Title = "Index";
}

<h2>
    DF Accountancy
</h2>
<div>

<fieldset>
<legend>About us</legend>

@foreach (data in Model)
{

<table>
    <tr>
        <td rowspan="2" width="50%">
            <b>
                Suspendisse lectus massa, feugiat at cursus ac, sollicitudin a metus.     Quisque adipiscing commodo sem vitae eleifend. 
            Maecenas ante risus, hendrerit ac tempor et, feugiat eu sapien. Sed sem massa, sodales a varius sit amet, porta in 
            turpis. Duis ullamcorper magna sed risus lobortis luctus. Quisque volutpat enim ut erat tristique sit amet posuere 
            sem ullamcorper. Nulla consequat lectus in sapien sagittis cursus. Quisque elit augue, luctus sed semper non, fringilla 
            sed quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce vitae 
            augue quis nisi tincidunt ullamcorper. Duis posuere ultricies turpis at dictum. Vivamus at odio eros. Nunc orci 
            lectus, ornare non tincidunt sed, venenatis id lorem. Nulla ullamcorper, leo quis pellentesque sollicitudin, dui 
            libero vehicula lectus, lobortis consequat orci dui in augue. Ut gravida enim convallis sem luctus sit amet eleifend 
            lorem malesuada. Suspendisse in augue diam, eu laoreet diam.
            </b>
            </td>
            <td>
                <div class="display-field">
                    @Html.Raw(data.para1.Replace(Environment.NewLine, "<br/>"))
                </div>
            </td>
        </tr>
        <tr>    
            <td>
                <div class="display-field">
                    @Html.Raw(data.para2.Replace(Environment.NewLine, "<br/>"))
                </div>
            </td>
        </tr>
</table>
}

        </fieldset>
</div>

==========================================

==========================================

The full Update View page code

完整的更新视图页面代码

@model DFAccountancy.Models.Data

@{
    ViewBag.Title = "Update";
    }



<h2>Update</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">    </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

<script type="text/javascript">
    $(function () { $("#cl_button1").click(function () { $("#para1").val(""); }); });
    $(function () { $("#cl_button2").click(function () { $("#para2").val(""); }); });
</script>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>Data</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.para1)
    </div>
    <div class="editor-field">
        @Html.TextAreaFor(model => model.para1, new { cols = 75, @rows = 5 })
        @Html.ValidationMessageFor(model => model.para1)
        <input id="cl_button1" type="button" value="Clear Paragraph" />
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.para2)
    </div>
    <div class="editor-field">
        @Html.TextAreaFor(model => model.para2, new { cols = 75, @rows = 5 })
        @Html.ValidationMessageFor(model => model.para2)
        <input id="cl_button2" type="button" value="Clear Paragraph" />
    </div>



    <p>
        <input type="submit" value="Update" />
        <input type="reset" value="Re-Set to begining" />
    </p>

</fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

采纳答案by jrummell

When displaying the field as html, it will not include line breaks since they are treated as spaces in html markup. You could replace them with <br/>. It would look something like this:

将字段显示为 html 时,它将不包括换行符,因为它们在 html 标记中被视为空格。你可以用<br/>. 它看起来像这样:

<div class="display-field">
   @Html.Raw(Model.para1.Replace(Environment.NewLine, "<br/>"))
</div>

Or you could display it as preformatted text, which will preserve white space:

或者您可以将其显示为预先格式化的文本,这将保留空白:

<div class="display-field">
    <pre>
        @Model.para1
    </pre>
</div>

UpdateIf your model is IEnumerable<T>:

更新如果您的模型是IEnumerable<T>

@foreach (var data in Model)
{
    <div class="display-field">
       @Html.Raw(data.para1.Replace(Environment.NewLine, "<br/>"))
    </div>
}

or

或者

@foreach (var data in Model)
{
    <div class="display-field">
        <pre>
            @data.para1
        </pre>
    </div>
}

回答by D Stanley

I don't know that it matters when savingthe data - I assume it's just used for choosing the visualizationof the member, but try moving your MultiLineText attribute to the string fields:

我不知道保存数据时是否重要- 我假设它只是用于选择成员的可视化,但尝试将 MultiLineText 属性移动到字符串字段:

public class Data
{
    public int ID { get; set; }
    [DataType(DataType.MultilineText)]
    public string para1 { get; set; }
    [DataType(DataType.MultilineText)]
    public string para2 { get; set; }
}

回答by user653649

Your problem probably isn't in the textarea. When displaying the input back on the home page, are you doing it within pre tags? If not, line breaks and formatting are ignored.

您的问题可能不在 textarea 中。当在主页上显示输入时,您是否在 pre 标签中执行此操作?如果不是,则忽略换行符和格式。

回答by Simon Edstr?m

The linebreak inside a textbox is CrLfso the content is not populated to a textbox the next time they will seems to disapper. However if you look into the HTML source you will find that they exist.

文本框内的换行符是CrLf这样的,下次它们似乎消失时,内容不会填充到文本框。但是,如果您查看 HTML 源代码,您会发现它们存在。

But because a line break isn't equal to a <br/>it will be a bit confusing.

但是因为换行符不等于 a<br/>它会有点混乱。

So what people are doing is to replace the CrLfto HTML BR like this:

所以人们正在做的是CrLf像这样替换HTML BR:

string ContentToDatabase = input.replace(Environment.NewLine, "<br/>")

If you open the same content in the textarea again you will see <br/>insteed of linebreaks, so you have to convert it back.

如果您再次在 textarea 中打开相同的内容,您将看到<br/>换行符,因此您必须将其转换回来。

string contentToEdit = fromDatabase.replace("<br/>",Environment.NewLine)

回答by brenton

I have run into a similar situation with this, needing to be able to add an entire article into a database from MVC3 and text areas. There are many ways you could go about this, but the simplest I've found is to turn off the ValidateInput (do NOT do this if you are opening up this to the public...this could cause cross site scripting and all sorts of nasties, make sure you validate the users).

我遇到了类似的情况,需要能够将整篇文章从 MVC3 和文本区域添加到数据库中。有很多方法可以解决这个问题,但我发现最简单的方法是关闭 ValidateInput(如果您向公众开放,请不要这样做......这可能会导致跨站点脚本和各种讨厌,请确保您验证用户)。

    [HttpPost]
    [AuthRole(Role = "Administrator")]  //Created Validataion so inaccessible from outside
    [ValidateInput(false)]      
    public ActionResult Update(Data data)       
    {       
        if (ModelState.IsValid)       
        {       
            data.ID = 1; //EF need to know which row to update in the database.       
            db.Entry(data).State = EntityState.Modified;       
            db.SaveChanges();       
            return RedirectToAction("Index", "Home");       
        }       
        return View(data);       
    }    

If you put a breakpoint in the data, you should see the newline's character ('\r\n') within VStudio. You can this replace that particular character with whatever you'd like (I'd suggest Environment.Newline if this isn't posting back to HTML).

如果在数据中放置断点,您应该会在 VStudio 中看到换行符 ('\r\n')。你可以用你喜欢的任何东西替换那个特定的字符(如果这不是回发到 HTML,我建议使用 Environment.Newline)。

                data.dataString = dataString.Replace(@"\r\n", Environment.Newline);
                //Or change Newline to "<br />" if posting to HTML

回答by Kevin

Don't manipulate the data at all. When you display it just wrap it in <pre></pre>

根本不要操纵数据。当您显示它时,只需将其包装在 <pre></pre> 中

Example: <pre>@Model.Data</pre>

例子: <pre>@Model.Data</pre>

This will preserve the carriage returns

这将保留回车

回答by Greg Little

Pre works fine, BUT it takes some "odd" formatting.

Pre 工作正常,但它需要一些“奇怪”的格式。

    <pre>
        @data.para1
    </pre>

This sort of works, Except it indents the first line by the 8 spaces ahead of the @ (not right justified as it might appear at a glance)

这种作品,除了它将第一行缩进@前面的 8 个空格(不正确,因为它可能一目了然)

    <pre>
@data.para1
    </pre>

This works well, but still has some stray returns.

这很有效,但仍然有一些杂散的回报。

<pre>@data.para1</pre>

This seems to be just right.

这似乎刚刚好

回答by Sum None

Here's what I ended up doing which I think is basically the same as the <pre>tag but without the ugly bootstrap formatting (i.e. border, off white back-ground color, weird font style, etc)

这是我最终做的事情,我认为它与<pre>标签基本相同,但没有丑陋的引导程序格式(即边框、灰白色背​​景颜色、奇怪的字体样式等)

CSS:

CSS:

.multi-line{
   white-space: pre-wrap;
}

View:

看法:

<div class="multi-line">@Html.DisplayFor(model => model.Description)</div>
<div class="multi-line">@data.para</div>

Make sure there are no spaces between your div element and your html helper or those will show up too as someone else mentioned in the above answers with the <pre>tag.

确保您的 div 元素和您的 html helper 之间没有空格,否则这些空格也会显示为上述带有<pre>标签的答案中提到的其他人。

回答by Hemant Ramphul

public class YourClass
{
    public int Id { get; set; }

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

@Html.TextAreaFor(m => m.paragraph, new { @class = "form-control", @rows = 5 })