Unable to access div content from C# - c#

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?

Related

Populating a span with a string including a linked email [duplicate]

What is the difference between innerHTML, innerText and value in JavaScript?
The examples below refer to the following HTML snippet:
<div id="test">
Warning: This element contains <code>code</code> and <strong>strong language</strong>.
</div>
The node will be referenced by the following JavaScript:
var x = document.getElementById('test');
element.innerHTML
Sets or gets the HTML syntax describing the element's descendants
x.innerHTML
// => "
// => Warning: This element contains <code>code</code> and <strong>strong language</strong>.
// => "
This is part of the W3C's DOM Parsing and Serialization Specification. Note it's a property of Element objects.
node.innerText
Sets or gets the text between the start and end tags of the object
x.innerText
// => "Warning: This element contains code and strong language."
innerText was introduced by Microsoft and was for a while unsupported by Firefox. In August of 2016, innerText was adopted by the WHATWG and was added to Firefox in v45.
innerText gives you a style-aware, representation of the text that tries to match what's rendered in by the browser this means:
innerText applies text-transform and white-space rules
innerText trims white space between lines and adds line breaks between items
innerText will not return text for invisible items
innerText will return textContent for elements that are never rendered like <style /> and `
Property of Node elements
node.textContent
Gets or sets the text content of a node and its descendants.
x.textContent
// => "
// => Warning: This element contains code and strong language.
// => "
While this is a W3C standard, it is not supported by IE < 9.
Is not aware of styling and will therefore return content hidden by CSS
Does not trigger a reflow (therefore more performant)
Property of Node elements
node.value
This one depends on the element that you've targeted. For the above example, x returns an HTMLDivElement object, which does not have a value property defined.
x.value // => null
Input tags (<input />), for example, do define a value property, which refers to the "current value in the control".
<input id="example-input" type="text" value="default" />
<script>
document.getElementById('example-input').value //=> "default"
// User changes input to "something"
document.getElementById('example-input').value //=> "something"
</script>
From the docs:
Note: for certain input types the returned value might not match the
value the user has entered. For example, if the user enters a
non-numeric value into an <input type="number">, the returned value
might be an empty string instead.
Sample Script
Here's an example which shows the output for the HTML presented above:
var properties = ['innerHTML', 'innerText', 'textContent', 'value'];
// Writes to textarea#output and console
function log(obj) {
console.log(obj);
var currValue = document.getElementById('output').value;
document.getElementById('output').value = (currValue ? currValue + '\n' : '') + obj;
}
// Logs property as [propName]value[/propertyName]
function logProperty(obj, property) {
var value = obj[property];
log('[' + property + ']' + value + '[/' + property + ']');
}
// Main
log('=============== ' + properties.join(' ') + ' ===============');
for (var i = 0; i < properties.length; i++) {
logProperty(document.getElementById('test'), properties[i]);
}
<div id="test">
Warning: This element contains <code>code</code> and <strong>strong language</strong>.
</div>
<textarea id="output" rows="12" cols="80" style="font-family: monospace;"></textarea>
Unlike innerText, though, innerHTML lets you work with HTML rich text and doesn't automatically encode and decode text. In other words, innerText retrieves and sets the content of the tag as plain text, whereas innerHTML retrieves and sets the content in HTML format.
InnerText property html-encodes the content, turning <p> to <p>, etc. If you want to insert HTML tags you need to use InnerHTML.
In simple words:
innerText will show the value as is and ignores any HTML formatting which may
be included.
innerHTML will show the value and apply any HTML formatting.
Both innerText and innerHTML return internal part of an HTML element.
The only difference between innerText and innerHTML is that: innerText return HTML element (entire code) as a string and display HTML element on the screen (as HTML code), while innerHTML return only text content of the HTML element.
Look at the example below to understand better. Run the code below.
const ourstring = 'My name is <b class="name">Satish chandra Gupta</b>.';
document.getElementById('innertext').innerText = ourstring;
document.getElementById('innerhtml').innerHTML = ourstring;
.name {
color:red;
}
<p><b>Inner text below. It inject string as it is into the element.</b></p>
<p id="innertext"></p>
<br>
<p><b>Inner html below. It renders the string into the element and treat as part of html document.</b></p>
<p id="innerhtml"></p>
var element = document.getElementById("main");
var values = element.childNodes[1].innerText;
alert('the value is:' + values);
To further refine it and retrieve the value Alec for example, use another .childNodes[1]
var element = document.getElementById("main");
var values = element.childNodes[1].childNodes[1].innerText;
alert('the value is:' + values);
In terms of MutationObservers, setting innerHTML generates a childList mutation due to the browsers removing the node and then adding a new node with the value of innerHTML.
If you set innerText, a characterData mutation is generated.
innerText property sets or returns the text content as plain text of the specified node, and all its descendants, whereas the innerHTML property gets and sets the plain text or HTML contents in the elements. Unlike innerText, innerHTML lets you work with HTML rich text and doesn’t automatically encode and decode text.
InnerText will only return the text value of the page with each element on a newline in plain text, while innerHTML will return the HTML content of everything inside the body tag, and childNodes will return a list of nodes, as the name suggests.
The innerText property returns the actual text value of an html element while the innerHTML returns the HTML content. Example below:
var element = document.getElementById('hello');
element.innerText = '<strong> hello world </strong>';
console.log('The innerText property will not parse the html tags as html tags but as normal text:\n' + element.innerText);
console.log('The innerHTML element property will encode the html tags found inside the text of the element:\n' + element.innerHTML);
element.innerHTML = '<strong> hello world </strong>';
console.log('The <strong> tag we put above has been parsed using the innerHTML property so the .innerText will not show them \n ' + element.innerText);
console.log(element.innerHTML);
<p id="hello"> Hello world
</p>
To add to the list, innerText will keep your text-transform, innerHTML wont.
#rule:
innerHTML
write: whatever String you write to the ele.innerHTML, ele (the code of the element in the html file) will be exactly same as it is written in the String.
read : whatever you read from the ele.innerHTML to a String, the String will be exactly same as it is in ele (the html file).
=> .innerHTML will not make any modification for your read/write
innerText
write: when you write a String to the ele.innerText, any html reserved special character in the String will be encoded into html format first, then stored into the ele.
eg: <p> in your String will become <p> in the ele
read : when you read from the ele.innerText to a String,
any html reserved special character in the ele will be decoded back into a readable text format,
eg: <p> in the ele will become back into <p> in your String
any (valid) html tag in the ele will be removed -- so it becomes "plain text"
eg: if <em>you</em> can in the ele will become if you can in your String
about invalid html tag
if there is an invalid html tag originally in the ele (the html code), and you read from.innerText, how does the tag gets removed?
-- this ("if there is an invalid html tag originally") should not (is not possible to) happen
but its possible that you write an invalid html tag by .innerHTML (in raw) into ele -- then, this may be auto fixed by the browser.
dont take (-interpret) this as step [1.] [2.] with an order
-- no, take it as step [1.] [2.] are executed at the same time
-- I mean, if the decoded characters in [1.] will form a new tag after the conversion, [2.] does not remove it
(-- cuz [2.] considers what characters are in the ele during the conversion, not the characters they become into after the conversion)
then stored into the String.
jsfiddle: with explanation
(^ this contains much more explanations in comments of the js file, + output in console.log
below is a simplified view, with some output.
(try out the code yourself, also there is no guarantee that my explanations are 100% correct.))
<p id="mainContent">This is a <strong>sample</strong> sentennce for Reading.</p>
<p id="htmlWrite"></p>
<p id="textWrite"></p>
// > #basic (simple)
// read
var ele_mainContent = document.getElementById('mainContent');
alert(ele_mainContent.innerHTML); // This is a <strong>sample</strong> sentennce for Reading. // >" + => `.innerHTML` will **not make any modification** for your read/write
alert(ele_mainContent.innerText); // This is a sample sentennce for Reading. // >" 2. any (valid) `html tag` in the `ele` will be **removed** -- so it becomes "plain text"
// write
var str_WriteOutput = "Write <strong>this</strong> sentence to the output.";
var ele_htmlWrite = document.getElementById('htmlWrite');
var ele_textWrite = document.getElementById('textWrite');
ele_htmlWrite.innerHTML = str_WriteOutput;
ele_textWrite.innerText = str_WriteOutput;
alert(ele_htmlWrite.innerHTML); // Write <strong>this</strong> sentence to the output. // >" + => `.innerHTML` will **not make any modification** for your read/write
alert(ele_htmlWrite.innerText); // Write this sentence to the output. // >" 2. any (valid) `html tag` in the `ele` will be **removed** -- so it becomes "plain text"
alert(ele_textWrite.innerHTML); // Write <strong>this</strong> sentence to the output. // >" any `html reserved special character` in the String will be **encoded** into html format first
alert(ele_textWrite.innerText); // Write <strong>this</strong> sentence to the output. // >" 1. any `html reserved special character` in the `ele` will be **decoded** back into a readable text format,
// > #basic (more)
// write - with html encoded char
var str_WriteOutput_encodedChar = "What if you have <strong>encoded</strong> char in <strong>the</strong> sentence?";
var ele_htmlWrite_encodedChar = document.getElementById('htmlWrite_encodedChar');
var ele_textWrite_encodedChar = document.getElementById('textWrite_encodedChar');
ele_htmlWrite_encodedChar.innerHTML = str_WriteOutput_encodedChar;
ele_textWrite_encodedChar.innerText = str_WriteOutput_encodedChar;
alert(ele_htmlWrite_encodedChar.innerHTML); // What if you have <strong>encoded</strong> char in <strong>the</strong> sentence?
alert(ele_htmlWrite_encodedChar.innerText); // What if you have <strong>encoded</strong> char in the sentence?
alert(ele_textWrite_encodedChar.innerHTML); // What if you have &lt;strong&gt;encoded&lt;/strong&gt; char in <strong>the</strong> sentence?
alert(ele_textWrite_encodedChar.innerText); // What if you have <strong>encoded</strong> char in <strong>the</strong> sentence?
// > #note-advance: read then write
var ele__htmlRead_Then_htmlWrite = document.getElementById('htmlRead_Then_htmlWrite');
var ele__htmlRead_Then_textWrite = document.getElementById('htmlRead_Then_textWrite');
var ele__textRead_Then_htmlWrite = document.getElementById('textRead_Then_htmlWrite');
var ele__textRead_Then_textWrite = document.getElementById('textRead_Then_textWrite');
ele__htmlRead_Then_htmlWrite.innerHTML = ele_mainContent.innerHTML;
ele__htmlRead_Then_textWrite.innerText = ele_mainContent.innerHTML;
ele__textRead_Then_htmlWrite.innerHTML = ele_mainContent.innerText;
ele__textRead_Then_textWrite.innerText = ele_mainContent.innerText;
alert(ele__htmlRead_Then_htmlWrite.innerHTML); // This is a <strong>sample</strong> sentennce for Reading.
alert(ele__htmlRead_Then_htmlWrite.innerText); // This is a sample sentennce for Reading.
alert(ele__htmlRead_Then_textWrite.innerHTML); // This is a <strong>sample</strong> sentennce for Reading.
alert(ele__htmlRead_Then_textWrite.innerText); // This is a <strong>sample</strong> sentennce for Reading.
alert(ele__textRead_Then_htmlWrite.innerHTML); // This is a sample sentennce for Reading.
alert(ele__textRead_Then_htmlWrite.innerText); // This is a sample sentennce for Reading.
alert(ele__textRead_Then_textWrite.innerHTML); // This is a sample sentennce for Reading.
alert(ele__textRead_Then_textWrite.innerText); // This is a sample sentennce for Reading.
// the parsed html after js is executed
/*
<html><head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<p id="mainContent">This is a <strong>sample</strong> sentennce for Reading.</p>
<p id="htmlWrite">Write <strong>this</strong> sentence to the output.</p>
<p id="textWrite">Write <strong>this</strong> sentence to the output.</p>
<!-- P2 -->
<p id="htmlWrite_encodedChar">What if you have <strong>encoded</strong> char in <strong>the</strong> sentence?</p>
<p id="textWrite_encodedChar">What if you have &lt;strong&gt;encoded&lt;/strong&gt; char in <strong>the</strong> sentence?</p>
<!-- P3 #note: -->
<p id="htmlRead_Then_htmlWrite">This is a <strong>sample</strong> sentennce for Reading.</p>
<p id="htmlRead_Then_textWrite">This is a <strong>sample</strong> sentennce for Reading.</p>
<p id="textRead_Then_htmlWrite">This is a sample sentennce for Reading.</p>
<p id="textRead_Then_textWrite">This is a sample sentennce for Reading.</p>
</body></html>
*/
innerhtml will apply html codes
innertext will put content as text so if you have html tags it will show as text only
1)innerHtml
sets all the html content inside the tag
returns all the html content inside the tag
includes styling + whitespaces
2)innerText
sets all the content inside the tag (with tag wise line breaks)
returns all html content inside the tag (with tag wise line breaks)
ignores tags (shows only text)
ignores styling + whitespaces
if we have style:"visibility:hidden;" inside tag
|_ innerText includes the styling -> hides content
3)textContent
sets all the content inside the tag (no tag wise line breaks)
returns all content inside the tag (no tag wise line breaks)
includes whitespaces
if we have style:"visibility:hidden;" inside tag
|_ textContent ignores the styling -> shows content
textContent has better performance because its value is not parsed as HTML.

How to save line breaks after parsing?

anglesharp - 0.9.11
On the page in the browser, the text is displayed as:
String_1.
String_2.
String_3.
String_4.
Parsing result:
String_1.String_2.String_3.String_4.
Page layout:
<div class="adv-point view-adv-point"><span>String_1. <br><br>String_2.<br>String_3.<br>String_4.</span></div>
I use code to parse:
var text = document.QuerySelectorAll("div:nth-child(4) >div:nth-child(3) > div.adv-point.view-adv-point");
text = items[0].TextContent.Trim();
Question
How to make the result of parsing with line breaks?
In other words, the result of the parsing should be:
String_1.
String_2.
String_3.
String_4.
I think if you use innerText here then it will work fine for you. Here is the code
var x = document.querySelectorAll("div:nth-child(4) >div:nth-child(3) > div.adv-point.view-adv-point");
console.log(x[0].innerText);
Try this-
var text=document.querySelectorAll(".view-adv-point span")[0].innerText;
If you log/alert text, you will see that the line break is present.
If you want to replace <br> with \n, then you can do this-
var text=document.querySelectorAll(".view-adv-point span")[0].innerHTML;
text = text.replace(/<br>/g, '\n');
But i believe this will return the same value as the first approach

<br/> not being displayed on text string replacement and then put into placeholder

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!

Replace string with a control

I have a string with special characters insert in different places. For example:
string myString = "This is a textbox: ##";
I would like to replace the ## with a control (namely, a textbox).
The Replace method only allows the string to be replaced with another string or character (understandably). But what would be the best way to dynamically replace the ## with a control in its position?
I was thinking maybe I could replace it with HTML markup which would be executed, but not quite sure how that would be achieved.
Thanks
EDIT: To clarify some details. The strings are being retrieved from a database, so I can't use the PlaceHolder control. The user selects a string from a drop-down list. The value of the item is the string with special characters. When the postback occurs from the item selection, I would like to display the string on the site, but replace the special characters with a fully working control (in this case, a textbox)
Consider leveraging the TextBox's Render() method. That'll get you the HTML that would be output from that TextBox.
You can then use that string to be the replacement text to replace the ## portion of your string.
TextBox Render() on MSDN
var myTxtBox = new TextBox();
myTxtBox.Text = "Hello World";
//implement the Render code in here
string myRenderedTextBoxHTML = RenderIt(myTxtBox);
string myString = "This is a textbox: " + myRenderedTextBoxHTML;
I'm unsure ViewState would be available for this control or not.
Something like this:
Panel panel = new Panel();
string myString = "This is a textbox: ##";
// some parsing logic
string[] arr = { "This is a textBox", "##" };
foreach(var item in arr)
{
if (item == "##"){
TextBox tb = new TextBox();
panel.Controls.Add(tb);
}
else{
Label l = new Label();
l.Text = item;
panel.Controls.Add(l);
}
}
your_plaaceholder.Controls.Add(panel);
myString = string.Replace("##", "<input type='text' />");
Note that this is not a control: it will just be an html element that won't be wired up on the server side later. And depending on what you do with the string maybe not even that much, as some controls (like label) will automatically escape your < and > characters.
If you really want a fully-working asp.net control there we need to know more about how you are adding that string to the page.
You could indeed replace it with markup:
string mystring = "This is a textbox: ##".Replace("##", "<input type='text'/>");
Response.Write(mystring);
I'm not sure why you would want to do this, though. Why not use a PlaceHolder control and just stick a TextBox in it in the code behind?
What Sash said, BUT make sure you put that in the Page.Init() every time if you wish to take advantage of viewstate.

Show new lines from text area in ASP.NET MVC

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" })

Categories

Resources