开发者

Problems with TEXTAREA line breaks in ASP.NET MVC 2

开发者 https://www.devze.com 2023-03-12 09:38 出处:网络
I really don\'t think this has anything to do with ASP.NET MVC 2 itself, but I mention that as it is the environment I am working in and at least one aspect of my problem is connected to the way MVC 2

I really don't think this has anything to do with ASP.NET MVC 2 itself, but I mention that as it is the environment I am working in and at least one aspect of my problem is connected to the way MVC 2 behaves. My problem is this:

I have a TEXTAREA element on a form that allows multiple lines of data to be entered. When the form is posted back to the server (using IE8), I can see that the data is formatted as "A\n\rB\n\rC\n\rD". I then save this data to a database table where it appears exactly the same way. However, when I come back to the page at a later time, loading the data from the database and setting it as the value of the TEXTAREA element, it displays the "\n\r" as literal characters instead of line breaks!

As a side note, with ASP.NET MVC, if I follow the standard if (!ModelState.IsValid) return View(viewModel); approach, the TEXTAREA displays fine when re-rendering the same form due to a validation error. This tells me that the problem must be related to persisting and retrieving the data to/from the (SQL Server) database.

I have th开发者_开发技巧e same display problem in FireFox and Chrome with the notable difference being that the data is formatted as "A\r\nB\r\nC\r\nD" when submitted from those browsers.

With these differences in behavior, how can I handle persisting multi-line data from a TEXTAREA that will render properly in ALL browsers?


You should replace \r\n char with
tag and create a MvcHtmlString when you want render the text, I use this:

@(MvcHtmlString.Create(Model.Text.Replace("\r\n","<br/>").Replace("\n\r","<br/>)))

Model.Text is a text from an TextArea, I've tested this line of code and it works as well on all five major browsers (IE, FF, Chrome, Opera, Safari).


I haven't found an actual solution but have implemented a work around.

When I set the property on my object to the submitted value from the TEXTAREA, I perform a regular expression replacement on the text to convert whatever characters are returned from the browser to '\n' which appears to work as a line break in all browsers I checked (IE8, Chrome & FireFox). Here is the code I'm using (in .NET):

cleanValue = Regex.Replace(value, "(\\n|\\\\n|\\r|\\\\r)+", "\n", RegexOptions.IgnoreCase);
0

精彩评论

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

关注公众号