Getting the HTML Markup from a dynamically constructed div - c#

How can I get the markup for something I created like this
Div MyDiv = new Div("Test");
I essentially want to get a string with the contents
string SomeString = "<div>Test</div>";
Or maybe even
string SomeString = "<div id="MyDiv">Test</div>;
Is there any way I can do that?

One option is to give the div an id and a runat="server" attribute. If\when the page is posted back to the codebehind, use the InnerHTML property. Example:
<div id="myDiv" runat="server" />
And in your codebehind
string contents = myDiv.InnerHTML;
If you only need this data client side, use javascript, like mentioned in the comments above. You can use the following code:
var x = document.getElementById('myDiv').innerHTML;
If you already have jQuery, then:
var x = $('myDiv').html();

Related

How to get text from a div tag?

I am trying to get text from div and put it in a text document using selenium c#. I cant seem to capture the text from div in variable
<div data-tid="messageContent" dir="auto"><div>new doc</div></div>
I tried these:
var puttingDataInDoc = driver.FindElement(By.XPath("//*[#data-tid='messageContent']")).GetAttribute();
var puttingDataInDoc = driver.FindElement(By.XPath("//*[#data-tid='messageContent']")).Text();
var puttingDataInDoc = driver.FindElement(By.XPath("//*[#data-tid='messageContent']")).Text;
Any suggestions please?
Text is a property, not method
var puttingDataInDoc = driver.FindElement(By.XPath("//*[#data-tid='messageContent']/div")).Text;
GetAttribute() needs a parameter specifying the attribute to fetch
var puttingDataInDoc = driver.FindElement(By.XPath("//*[#data-tid='messageContent']/div")).GetAttribute("textContent");
// or
var puttingDataInDoc = driver.FindElement(By.XPath("//*[#data-tid='messageContent']/div")).GetAttribute("innerHTML");
You should also target the child <div>, the text is there.

How to get selected value/text from HTML Select in codebehind

I'm trying to get my selected value/text from and HTML select option but I can't get it! I already tried with answers posted in this website but none works.
This my code:
<select id="Select" name="Select" runat="server">
<option value="1">Option 1</option>
</select>
I tried these C# codes:
//With this I get Index out of range error message:
string name = nombre.Items[nombre.SelectedIndex].Text;
//With this I get nothing:
string name = this.nombre.Value.ToString();
//Nothing here:
string name = this.nombre.Value;
What can I do? It's necessary using html select control.
to get a value,
string sVal = dropdownName.Items[dropdownName.SelectedIndex].Value;
to get a text,
string sText= dropdownName.Items[dropdownName.SelectedIndex].Text;
You would probably be better off using an asp:DropDownList, but you can still reference straight selects. Here's code that will grab the value and text from your HTML above:
string value = Select.Items[Select.SelectedIndex].Value;
string text = Select.Items[Select.SelectedIndex].Text;
Be sure you're using the correct ID name (Select is shown in your html, but nombre is used in your code behind).

How Can DeActivate Razor Html Encoding ?

In Razor view I have a Javascript function. This function take 2 URLS String in arguments and call AJAX to do operation.
When I generated Url string in Razor, Razor change the URLS. Like changed & to & and damage my query strings which used in my URL address. Also Html.Raw() has not work in this case.
What can I do ?
EXAMPLE:
In my Razor editor:
<a href="#" style="color:#0564c1;" onclick="PopUpStart('POST','','',200,100,'#(Html.Raw(address+"/index/?id="+baseObject.Id+"&"+"type="+dataTypeInt))','#Html.Raw(address + "/cancel/?id="+baseObject.Id+"&type="+dataTypeInt )','ReloadPage',true);return false;">
Edit
</a>
In result :
<a href="#" style="color:#0564c1;" onclick="PopUpStart('POST','','',200,100,'/PdfInstanceEdit/index/?id=1&type=270','/PdfInstanceEdit/cancel/?id=1`&`type=270','ReloadPage',true);return false;">
Edit
</a>
The URL address like :
address+"/index/?id="+baseObject.Id+"&"+"type="+dataTypeInt
Change to :
/PdfInstanceEdit/index/?id=1&type=270
In other world character & => &
Its usually a bad idea to try and combine server code and client strings inside the quotes of a property (ie onclick="something#(something())" )
Its better to just return the entire lot in a server side function
Here's how I would rework your code:
<a href="#" style="color:#0564c1;"
onclick="#Html.Raw(
String.Format(
"PopUpStart('POST','','',200,100,'{0}','{1}','ReloadPage',true);return false;"
, Url.Action("index",address,new{id = baseObject.Id, type = dataTypeInt})
, Url.Action("cancel",address,new{id = baseObject.Id, type = dataTypeInt})
)
)"/>
Edit
</a>
Also note the difference between #(Html.Raw()) and #Html.Raw() - you should use the latter!
As direct assignment of events such as onClick is frowned on these days, a better way to accomplish then may be through js:
Add a hidden field for Id and dataTypeInt to your page:
#Html.HiddenFor(model=> model.Id)
#Html.Hidden("dataTypeInt ", dataTypeInt)
Add an id to your anchor:
Edit
Then your script:
<script>
$(document).ready(function () {
readyLinks();
});
readyLinks = function(){
var id = $('#Id).val();
var dataType = $('#dataTypeInt').val();
var indexUrl = '/PdfInstanceEdit/index?id=' + id + '&type=' + dataType;
var cancelUrl = '/PdfInstanceEdit/cancel?id=' + id + '&type=' + dataType;
$('#editLink).on('click', function(){
PopUpStart('POST','','',200,100,indexUrl, cancelUrl,'ReloadPage',true);
return false;
});
};
</script>
You should use Html.Raw() as suggested in the comments, see the documentation.
As described in this thread, if you have a particular problem with the output encoded format, you could use the HttpUtility.HtmlDecode() function, see documentation.
#Html.Raw(HttpUtility.HtmlDecode(address+"/index/?id="+baseObject.Id+"&"+"type="+dataTypeInt))
But since this could be a solution I cannot address you problem precisely...
A friendly reminder: if you're trying to put a Javascript string inside an HTML attribute, the value must be encoded twice. It must first be Javascript-encoded, then that result must be HTML-encoded. You could inadvertently open an XSS hole in your site if you don't perform both encodings in the correct order.
Say you have a string s that you want to display to the client. You'd write your Razor markup as:
Click me
Note the explicit call to JavaScriptStringEncode. Then Razor's # syntax will auto-HtmlEncode this value before writing it to the response.

Is there a way to dynamically assign a CSS class to an MVC4 Html.Encode entry?

I have a simple field in one of my views that shows a sum for one of my columns using this code:
<p class="points-total" >#Html.Encode(ViewData["pointsTotal"])</p>
This is my controller code regarding pointsTotal:
pointsTotal = occurrences.Sum(o => o.Points);
ViewData["pointsTotal"] = pointsTotal.ToString();
I would like to assign a different class to this line based on the value of pointsTotal. For example if the total is over 50 points I'd like to assign it to class points-total-fifty.
I know I can do this on other HTML helpers like DisplayFor by doing this:
<p class="#(item.Total > 50 ? "points-total-fifty" :
"points-total")">#Html.DisplayFor(modelItem => item.Total)</p>
Is there a way to do the same thing with the Html.Encode helper?
Actually the code you put for your second example will work also with the Html.Encode helper as you are styling the <p> element. One way to do it for example:
#{
string cssClass = "points-total";
int? total = ViewData["pointsTotal"] as int?;
if (total.HasValue && total > 50)
{
cssClass = "points-total-fifty";
}
}
<p class="#cssClass" >#Html.Encode(ViewData["pointsTotal"])</p>

How do I get this div tag using selenium webdriver?

<div id="ctl00_ContentHolder_vs_ValidationSummary" class="errorblock">
<p><strong>The following errors were found:</strong></p>
<ul><input type="hidden" Name="SummaryErrorCmsIds" Value="E024|E012|E014" />
<li>Please select a title.</li>
<li>Please key in your first name.</li>
<li>Please key in your last name.</li>
</ul>
</div>
I want to capture the text having value of E024 E012 and E014 and write it in to an Excel file.
I tried the following but it doesn't work.
string val1 = driver.FindElement(By.XPath("//div[contains(#class, 'errorblock'/ value = 'E024|E012|E014'")).Text;
How can I do this?
In java -
String x = driver.findElement(By.name("SummaryErrorCmsIds")).getAttribute("Value"));
Better way is to use XPATH
driver.FindElement(By.XPath("...\li")).Text; (OR)
driver.FindElement(By.XPath("...\li")).GetAttribute("value");
Your problem is you're selecting the wrong elements. I have no idea what your html looks like but try looking into FindElements and try doing a lookup by 'li'
Take a look here: Using Selenium 2's IWebDriver to interact with elements on the page
I am not sure if this is what you meant but my example solution would be:
WebElement element = driver.findElement(By.className("errorblock")).findElement(By.tagName("ul"));
List<WebElement> values = element.findElements(By.tagName("li"))
for (WebElement value : values)
{
String valueString = value.getText();
//write to excel or whatever
}
Try this:
var div = driver.FindElement(By.XPath("//div[contains(#id, 'ValidationSummary')]"));
var targetElement = div.FindElement(By.XPath("//ul[contains(#name, 'SummaryErrorCmsIds')]"));
// or var targetElement = div.FindElement(By.TagName("input"))
And then get info you need from this element.
IN C# it should be as follows.
String var1= driver.FindElement(By.XPath("//div[contains(#id, 'ValidationSummary')]")).Text;

Categories