简体   繁体   English

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

[英]line breaks in textarea used in a MVC C# website app

I'm using ASP.net MVC C# in Visual Studio Web Dev. 我在Visual Studio Web Dev中使用ASP.net MVC C#。 I have a couple of textareas which are populated with data and then updated to a database record. 我有几个textareas填充了数据,然后更新到数据库记录。

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: View页面上的代码如下所示:

<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: 处理提交的Controller代码如下所示:

[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: 并且数据库的Model代码如下所示:

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 完整的Update View页面代码

@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>

When displaying the field as html, it will not include line breaks since they are treated as spaces in html markup. 将字段显示为html时,它不会包含换行符,因为它们在html标记中被视为空格。 You could replace them with <br/> . 你可以用<br/>替换它们。 It would look something like this: 它看起来像这样:

<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>

Update If 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>
}

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 这将保留回车

Pre works fine, BUT it takes some "odd" formatting. 前工作正常,但它需要一些“奇怪”的格式。

    <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 . 这似乎是正确的

I don't know that it matters when saving the data - I assume it's just used for choosing the visualization of 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; }
}

The linebreak inside a textbox is CrLf so the content is not populated to a textbox the next time they will seems to disapper. 文本CrLf的换行符是CrLf因此下次它们似乎消失时,内容不会填充到文本框中。 However if you look into the HTML source you will find that they exist. 但是,如果您查看HTML源代码,您会发现它们存在。

But because a line break isn't equal to a <br/> it will be a bit confusing. 但是因为断行不等于<br/>这将是一个有点混乱。

So what people are doing is to replace the CrLf to 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. 如果您在文字区域打开同一个内容再一次,你会看到<br/>换行符的insteed,所以你必须将其转换回。

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

Here's what I ended up doing which I think is basically the same as the <pre> tag but without the ugly bootstrap formatting (ie 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帮助器之间没有空格,否则这些空格也会像上面使用<pre>标签在上面的答案中提到的那样显示出来。

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 })

Your problem probably isn't in the textarea. 您的问题可能不在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. 如果不是,则忽略换行符和格式。

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. 我遇到了类似的情况,需要能够将整篇文章从MVC3和文本区域添加到数据库中。 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). 有很多方法你可以解决这个问题,但我发现最简单的方法就是关闭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. 如果在数据中放置断点,则应在VStudio中看到换行符的字符('\\ r \\ n')。 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). 你可以用你想要的任何东西替换那个特定的角色(我建议使用Environment.Newline,如果这不是回复到HTML)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM