I'm currently creating an application using ASP.NET MVC. I got some user input inside a textarea and I want to show this text with <br />s instead of newlines. In PHP there's a function called nl2br, that does exactly this. I searched the web for equivalents in ASP.NET/C#, but didn't find a solution that works for me.
The fist one is this (doesn't do anything for me, comments are just printed without new lines):
<%
string comment = Html.Encode(Model.Comment);
comment.Replace("\r\n", "<br />\r\n");
%>
<%= comment %>
The second one I found was this (Visual Studio tells me VbCrLf is not available in this context - I tried it in Views and Controllers):
<%
string comment = Html.Encode(Model.Comment);
comment.Replace(VbCrLf, "<br />");
%>
<%= comment %>
Try (not tested myself):
comment = comment.Replace(System.Environment.NewLine, "<br />");
UPDATED:
Just tested the code - it works on my machine
UPDATED:
Another solution:
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringReader sr = new System.IO.StringReader(originalString);
string tmpS = null;
do {
tmpS = sr.ReadLine();
if (tmpS != null) {
sb.Append(tmpS);
sb.Append("<br />");
}
} while (tmpS != null);
var convertedString = sb.ToString();
to view html tags like a DisplayFor
you need to use another method , in fact the mvc dosent allowed you to view tags in page
but you can used this to ignore this option
#Html.Raw(model => model.text)
good luck
If you have a Razor-based view , string with line breaks and want to show that text with the line-breaks intact in your view, you can do this without replacing all \r\n with "html br"-tags. Instead present the text in an element that has the style property white-space set to pre-line. You should really add a class like:
<span class="line-breaks">#Model.MyText</span>
.line-breaks {
white-space:pre-line;
}
Original Found #
https://kaliko.com/blog/text-line-breaks-in-asp.net-mvc-razor-view/
Please have a look this answer Replace Line Breaks in a String C# here.
#Html.Raw(#Model.Comment.RestoreFormatting())
and than...
public static class StringHelper
{
public static string RestoreFormatting(this string str)
{
return str.Replace("\n", "<br />").Replace("\r\n", "<br />");
}
}
I have the same issue and above all answer given the hint, not exactly help, that's why given the answer to help.
Replace "\n" strign with '', '\r\n','\n', nothing help and finally when replace "\r\n", it will work. (in display it like \n, but in database it store as \\n)
Old code
#Html.TextArea("MEPat_textPatNote", Model.MedicationPatCur, 4, 4, new { #class = "k-textbox", style = "width: 100%;", maxlength = "300" })
New code
#Html.TextArea("MEPat_textPatNote", Model.MedicationPatCur.PatNote== null? "": Model.MedicationPatCur.PatNote.Replace("\\n","\r\n"), 4, 4, new { #class = "k-textbox", style = "width: 100%;", maxlength = "300" })
Related
I am formatting my application to show the address related to a specific work ticket. Occasionally the address uses a second line. I don't want to use the following:
<%: ticket.ADDRESS2 %><br />
In this scenario, if the object is null or empty I still get the break and then I have a large space that looks funny.
I thought I could generate my own string and then turn it into a literal with something like this:
string str = ((Object)ticket.ADDRESS2 != "").ToString();
string sAdd2 = str + <br />;
myLiteral.Text = sAdd2;
But that doesn't actually help me out if the Object is null or empty (in fact, I don't even know if it works at all.
So then I tried this:
public string sAdd2
{
get
{
Object oAdd2 = ticket.ADDRESS2;
if (oAdd2 != null)
{
string sAdd2 = ((Object)ticket.ADDRESS2 != "").ToString();
}
else
{
string sAdd2 = ((Object)ticket.ADDRESS2 == "").ToString();
}
}
}
With this I get errors at the 'get' (not all code paths return a value). I feel like I am going way out of the way to do a simple thing. I just want to have my page show
Address Line 1
Address Line 2
City, State ZIP
or
Address Line 1
City, State ZIP
Anyone have any pointers? I've looked up "conditional breaks" but didn't get much of a useful return.
Use an if statement
<%if (!string.IsNullOrEmpty(ticket.ADDRESS2)) { %>
<%: ticket.ADDRESS2 %><br />
<%} %>
What I have done in the past – in an MVC project, but could easily be in code behind for WebForms – is:
var lines = new [] {
contact.Name,
contact.AddressLine1,
contact.AddressLine2,
contact.AddressLine3,
contact.PostCode
};
var address = String.Join("<br/>", lines.Where(l => !String.IsNullOrWhitespace(l));
and then use the appropriate method to write out address as a raw string.
Remove blank lines, then use string.Join() to add newlines.
// Get the address lines to be displayed
string[] lines = new string[]
{
ticket.Address1,
ticket.Address2,
ticket.Address3,
ticket.Address4,
ticket.ZipCode,
};
// Remove blank lines
IEnumerable<string> filledLines = lines.Where(s => !string.IsNullOrWhitespace(s));
// Add newlines between each line
string html = string.Join(#"<br />", filledLines);
I only see the space tags "\r\n "\r\n" for InnerHTML & InnerText properties and not the actual content. Where am i going wrong
RENDERED HTML:
<div id="urllist" runat="server">
http://test1t.com
<br></br>
http://test2.com
<br></br>
</div>
C#:
HtmlContainerControl list = (HtmlContainerControl)urllist;
string string1 = list.InnerHtml;
string string2 = list.InnerText;
//this didnt work either
string string1 = urllist.InnerHtml;
string string2 = urllist.InnerText;
If i remember correctly you have to use Controls[0] to find the literal control that contains the text:
var div = (HtmlGenericControl) urllist;
var lit = (LiteralControl) div.Controls[0];
string text = lit.Text;
Update: tested, it works. This is text:
http://test1t.com
<br></br>
http://test2.com
<br></br>
However, now i have tested it with your approach and it works also.
I would have added a comment, but I cannot add images in comments. See below, I've tested your code and it works:
Are you sure you don't check your result in a HTML page or that you are not altering your result in any way before you check it?
I have a field called Description in the front end form, it is a textarea where user can type/copy past the text which include line breaks aswell.
From asp.net all this data goes to sharepoint.
Now I have a search page which returns all these values from sharepoint using webserivices in the format of xml.
The problem is that all of the line breaks in the value in replaced with
I am trying to display the description field values to the label, but its not working I tried below things :
lblDesc.Text = xmlValuesPath.Attribute("ows_Description").Value.Replace("
", "\n");
lblDesc.Text = xmlValuesPath.Attribute("ows_Description").Value.Replace("
", "</p><p>");
The formatting works fine in a textbox, but nothing seems to be working, kindly help.
Did you clear out all HTML tags from it?
public static string ClearHTMLTagsFromString(string htmlString)
{
string regEx = #"\<[^\<\>]*\>";
string tagless = Regex.Replace(htmlString, regEx, string.Empty);
// remove rogue leftovers
tagless = tagless.Replace("<", string.Empty).Replace(">", string.Empty);
tagless = tagless.Replace("Body:", string.Empty);
return tagless;
}
Try to replace "
" with "<br/>" it should work in ASP.NET Label.
By default asp.net coverts it to \n .which at the run time wont be parsed by the html code to you just need to replace \n with ""
xmlValuesPath.Attribute("ows_Description").Value.Replace("\n", "</p><p>")
When I read in the data from SQL it has \r\n for the carriage returns, so I use .Replace to convert the \r\n's to <br/>'s but on display the <br/>'s are ignored. It works if I replace the \r\n's with <p></p> but this is not what I need.
The <br/>'s are being ignored and I need them to produce a newline.
Any insight as to why it is doing this or how to achieve what I am looking to do would be great!
EDIT: I've addressed the typo in the code below - but that isn't my question -at all-. I've asked about BR's and them displaying.
HTML
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
CODE-BEHIND
string strTempDetail = myReader["Detail"].ToString();
string strMoreTempDetail = strTempDetail.Replace("\r\n", "<br/>");
LiteralControl UserControlSpecialOffers = new LiteralControl(strMoreTempDetail.ToString());
PlaceHolder1.Controls.Add(UserControlSpecialOffers);
Thanks!
You have a typo in your code. You are assigning the original string into your control instead of the string containing your replacements.
change
LiteralControl UserControlSpecialOffers = new LiteralControl(strTempDetail.ToString());
to
LiteralControl UserControlSpecialOffers = new LiteralControl(strMoreTempDetail );
Because you're adding strTempDetail to your literal control, not strMoreTempDetail, which is the string where you performed the replacement.
You have the wrong string in this line
LiteralControl UserControlSpecialOffers = new LiteralControl(strTempDetail.ToString());
it should be
LiteralControl UserControlSpecialOffers = new LiteralControl(strMoreTempDetail);
Are you by any change reading your string from SQL Server? If had issues where a string read from an SQL server ntext column contained a '\n' instead of '\r\n' (even though '\r\n' was saved).
Try if string strMoreTempDetail = strTempDetail.Replace("\n", "<br/>") provides better results.
Or to be on the save side, replace both: string strMoreTempDetail = strTempDetail.Replace("\r\n", "<br/>").Replace("\n", "<br/>")
Someone else had modified the css file and put BR display:none; in the CSS. Of all the places!
I have a very simple asp:textbox with the multiline attribute enabled. I then accept just text, with no markup, from the textbox. Is there a common method by which line breaks and returns can be converted to <p> and <br/> tags?
I'm not looking for anything earth shattering, but at the same time I don't just want to do something like:
html.Insert(0, "<p>");
html.Replace(Enviroment.NewLine + Enviroment.NewLine, "</p><p>");
html.Replace(Enviroment.NewLine, "<br/>");
html.Append("</p>");
The above code doesn't work right, as in generating correct html, if there are more than 2 line breaks in a row. Having html like <br/></p><p> is not good; the <br/> can be removed.
I know this is old, but I couldn't find anything better after some searching, so here is what I'm using:
public static string TextToHtml(string text)
{
text = HttpUtility.HtmlEncode(text);
text = text.Replace("\r\n", "\r");
text = text.Replace("\n", "\r");
text = text.Replace("\r", "<br>\r\n");
text = text.Replace(" ", " ");
return text;
}
If you can't use HttpUtility for some reason, then you'll have to do the HTML encoding some other way, and there are lots of minor details to worry about (not just <>&).
HtmlEncode only handles the special characters for you, so after that I convert any combo of carriage-return and/or line-feed to a BR tag, and any double-spaces to a single-space plus a NBSP.
Optionally you could use a PRE tag for the last part, like so:
public static string TextToHtml(string text)
{
text = "<pre>" + HttpUtility.HtmlEncode(text) + "</pre>";
return text;
}
Your other option is to take the text box contents and instead of trying for line a paragraph breaks just put the text between PRE tags. Like this:
<PRE>
Your text from the text box...
and a line after a break...
</PRE>
Depending on exactly what you are doing with the content, my typical recommendation is to ONLY use the <br /> syntax, and not to try and handle paragraphs.
How about throwing it in a <pre> tag. Isn't that what it's there for anyway?
I know this is an old post, but I've recently been in a similar problem using C# with MVC4, so thought I'd share my solution.
We had a description saved in a database. The text was a direct copy/paste from a website, and we wanted to convert it into semantic HTML, using <p> tags. Here is a simplified version of our solution:
string description = getSomeTextFromDatabase();
foreach(var line in description.Split('\n')
{
Console.Write("<p>" + line + "</p>");
}
In our case, to write out a variable, we needed to prefix # before any variable or identifiers, because of the Razor syntax in the ASP.NET MVC framework. However, I've shown this with a Console.Write, but you should be able to figure out how to implement this in your specific project based on this :)
Combining all previous plus considering titles and subtitles within the text comes up with this:
public static string ToHtml(this string text)
{
var sb = new StringBuilder();
var sr = new StringReader(text);
var str = sr.ReadLine();
while (str != null)
{
str = str.TrimEnd();
str.Replace(" ", " ");
if (str.Length > 80)
{
sb.AppendLine($"<p>{str}</p>");
}
else if (str.Length > 0)
{
sb.AppendLine($"{str}</br>");
}
str = sr.ReadLine();
}
return sb.ToString();
}
the snippet could be enhanced by defining rules for short strings
I understand that I was late with the answer for 13 years)
but maybe someone else needs it
sample line 1 \r\n
sample line 2 (last at paragraph) \r\n\r\n [\r\n]+
sample line 3 \r\n
Example code
private static Regex _breakRegex = new("(\r?\n)+");
private static Regex _paragrahBreakRegex = new("(?:\r?\n){2,}");
public static string ConvertTextToHtml(string description) {
string[] descrptionParagraphs = _paragrahBreakRegex.Split(description.Trim());
if (descrptionParagraphs.Length > 0)
{
description = string.Empty;
foreach (string line in descrptionParagraphs)
{
description += $"<p>{line}</p>";
}
}
return _breakRegex.Replace(description, "<br/>");
}