Evgeniy Labunskiy
Evgeniy Labunskiy

Reputation: 2042

Break new Line problem - C# .NET MVC

It's good day today! But... :) I have the following problem: I have a controller that updates a type_text field in a Mysql DB. The user types text in texarea, clicks "Update" and, oh magic, the text is posted to the database. But without a break...

In the controller i have:

[Authorize]
[HttpPost]
public string EditComment(FormCollection formValues)
{
    var Commenter = User.Identity.Name;
    Int64 id = Convert.ToInt64(Request.Form["id"]);

    string formValue = Request.Form["value"];
    formValue = formValue.Replace("\r\n", "<br/>").Replace("\r", "<br/>");

    comments updateCommnets = db.comments.SingleOrDefault(d => d.id == id && d.commenterName == Commenter);
    updateCommnets.comment = formValue;
    db.SaveChanges();

    return formValue;
}

It's making me crazy for 2 days...

Can Somebody help me? Thanks a lot!

UPDATED

Upvotes: 2

Views: 3546

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

I would store the text as is in the database without converting \r\n to <br/>:

[Authorize]
[HttpPost]
public ActionResult EditComment(string value, long id)
{
    var commenter = User.Identity.Name;
    var updateCommnets = db.comments.SingleOrDefault(d => d.id == id && d.commenterName == commenter);
    updateCommnets.comment = value;
    db.SaveChanges();
    return Content(value, "text/plain");
}

Then I would write a custom HTML helper to format the values in the view if necessary to show those comments.

public static MvcHtmlString FormatComment(this HtmlHelper html, string comment)
{
    if (string.IsNullOrEmpty(comment))
    {
        return MvcHtmlString.Empty;
    }
    var lines = comment
        .Split(
            new string[] { Environment.NewLine }, 
            StringSplitOptions.None
        )
        .Select(x => HttpUtility.HtmlEncode(x))
        .ToArray();
    return MvcHtmlString.Create(string.Join("<br/>", lines));
}

and then in the view:

@Html.FormatComment(Model.Comment)

Upvotes: 6

Velter
Velter

Reputation: 2160

Do not convert the text that is sent to the database. Use:

@MvcHtmlString.Create(value)

Here's the manual

Upvotes: 5

Related Questions