开发者

Break new Line problem - C# .NET MVC

It's good day today! But... :) I have the following problem: I have a contro开发者_运维百科ller 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

  • I use jeditable to perform inline editing. Example of post string: value=Some+text%0ASome2+text2


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)


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

@MvcHtmlString.Create(value)

Here's the manual

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜