简体   繁体   中英

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

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.

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>

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:

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

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

Example: <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)

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

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. However if you look into the HTML source you will find that they exist.

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

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

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.

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)

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.

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

    [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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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