Javascript string formatting - c#

In my C# webapplication, I have to pass this below html string to a client side function by clicking on a server side button code. I am using Firefox browser.
htmlString is:
<div id='divPopUpToXyz.abc#def.com'>
<table>
<tr>
<td>
<img width='10' src='../images/cross.gif' onclick='deleteDiv(1,'ToXyz.abc#def.com','To')>
</td>
<td>
Xyz.abc#def.com
</td>
</tr>
</table>
</div>
On server side i am using this to call the required JS function:
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "returnValue('" + htmlString+ "');", true);
But I am getting an error like this:
"missing ) after argument list"
I checked through firebug, and found that the htmlstring gets distorted like this:
<div id='divPopUpToXyz.abc#def.com'>
<table>
<tbody>
<tr>
<td>
<img src="../images/cross.gif" onclick="deleteDiv(1," toXyz.abc#def.com','to')="" width="10">
</td>
<td>
Xyz.abc#def.com
</td>
</tr>
</tbody>
</table>
</div>
I am not getting why it is changing like this.
Please suggest some way out.

you are not passing the value you expect to be passing
onclick='deleteDiv(1,'ToXyz.abc#def.com','To'
is interpreted as two attributes
onclick='deleteDiv(1,'
ToXyz.abc#def.com','To'=""
because of the first ' following 1, is terminating the onclick attribute assignment
change the htmlString assignement to
var htmlString = HttpUtility.JavaScriptStringEncode(#"<div id='divPopUpToXyz.abc#def.com'><table><tr><td><img width='10' src='../images
/cross.gif' onclick='deleteDiv(1,""ToXyz.abc#def.com"",""To"")'>
</td><td>Xyz.abc#def.com</td>
</tr></table></div>");
and you should be good to go

Related

Error for bind data values in html.index with AngularJS

i am using AngularJS and I am not able to populate the data in index.view with the ng-repeat of angular.
I'll leave the code snippet for any help.
Remember, I have the status of the http 200 requests ok, just when I connect the data on the screen, I can not fill.
registerController.js
angular.module('Application').controller('registerController',
function($scope,
$http, registerService) {
$scope.registerUser = {};
$scope.GetAllRegisters = function () {
var registerServiceCall = registerService.GetRegisters();
registerServiceCall.then(function (results) {
$scope.registers = results.data;
}, function (error) {
$log.error('ERRO');
});
};
$scope.GetAllRegisters();
});
My service.js
angular.module('Application').factory('registerService', function ($http) {
return {
GetRegisters: function () {
return $http({
method: 'Get',
url: "http://localhost:51734/api/UserAPI"
})
},
};
});
And my index.html
<div class="row" style="">
<table class="table table-striped" style="">
<tbody>
<tr>
<th style="display:none">Id</th>
<th>Nome</th>
<th>Sobrenome</th>
<th>Ativo</th>
<th>Email</th>
<th>Editar</th>
<th>Remover</th>
</tr>
<tr ng-repeat="registerUser in registers" style="word-wrap: break-word;">
<td style="display:none">{{registerUser.UserId}}</td>
<td>{{registerUser.Name}}</td>
<td>{{registerUser.LastName}}</td>
<td><input type="checkbox" ng-model="registerUser.IsActive" disabled /></td>
<td>{{registerUser.Email}}</td>
<td>
<td>
</td>
</tr>
</tbody>
</table>
Any help or advice would be appreciated. Thanks
What is $scope.registers once the page loads?
As it stands right now your table will not render correctly because you cannot use ng-repeat on a tr because it will be inserted as a block-level element which will blow up your table. However, the data should still be inserted above your table. You will have to call ng-repeat on a custom directive to render the table properly.
Something like this:
<register-user-row ng-repeat="registerUser in registers"><register-user-row>
Then in the directive:
angular.module('Application').directive('regusterUserRow', function() {
return {
templateUrl: "directive path here",
restrict: "E",
scope: true
}
})
And the directive's html:
<tr style="word-wrap: break-word;">
<td style="display:none">{{registerUser.UserId}}</td>
<td>{{registerUser.Name}}</td>
<td>{{registerUser.LastName}}</td>
<td><input type="checkbox" ng-model="registerUser.IsActive" disabled /></td>
<td>{{registerUser.Email}}</td>
<td>
</td>
<td>
</td>
</tr>
Note: You were also missing a closing after your first link in the .

How to read values from two separate tags using C#

I have multiple tags, within each there are multiple tags and inside span tag there are bunch of inner tgs, for the reference i have attached the snapshot along with the question:
<div class="questionContainer field-type_single-select " id="abc" qbparent="0" fieldtype="single-select">
<span class="questionLabel">
<table class="guardAgainstInvalidMarkup">
<tbody>
<tr>
<td class="guardAgainstInvalidMarkup">
<span class="EDITPOPformlabel" align="right">
<font class="FONTMedium">test data</font>
</span>
</td>
<td class="helpLinkCell">
<span class="helpLink">
<span class="questionHelpText" />
</span>
</td>
</tr>
</tbody>
</table>
</span>
<span class="questionInput">
<div class="viewResponse">
<table class="guardAgainstInvalidMarkup">
<tbody>
<tr>
<td class="guardAgainstInvalidMarkup">test sample</td>
</tr>
</tbody>
</table>
</div>
</span>
<div class="clearBoth" />
</div>
I need to read value's of following tags
<font class="FONTMedium">test data</font> and
<td class="guardAgainstInvalidMarkup">test sample</td>
and create a map with values of these tags.
what i did is :
i used foreach loop on and obtain tags from them and kept going till i reach the tag from which i need value.
I want to know is there a easy way to accomplish these values.
any help will be much appreciated.
You can get whatever element you want using XPATH expressions.
Try below simple code. It gets the element which has font value "test data".
XmlDocument doc = new XmlDocument();
doc.Load("C:\\Users\\<xxxxx>\\Desktop\\14x\\div.xml");
XmlNode root = doc.DocumentElement;
XmlNode node = root.SelectSingleNode("descendant::span/table/tbody/tr/td/span[font='test data']");
This way you do not need to loop.
For documentation refer below link:
https://learn.microsoft.com/en-us/dotnet/standard/data/xml/select-nodes-using-xpath-navigation
You said "using C#" in your question but I can't see any runat="server" attribute...
So maybe you could achieve this using JavaScript? Something like:
$("span").each(function(){
var value = $(this).text(); // <- This holds every span content
// Do whatever with your span...
})

C# Selenium fails to get cell value from table based on tr and td tags

I don't seem to know why my code cannot get cell value instead it always throws exception saying Additional information: no such element: Unable to locate element: {"method":"xpath","selector":"html/body/div[2]/div[2]/table/tr[1]/td[0]"}
Below is my table HTML page.
<div class="tableBlock">
<table class="tableTag">
<tr>
<th>Name</th>
<th>Favorite Color</tr>
<tr>
<td>Ken Master</td>
<td>
<input type="text" value="yellow" class="favoriteColorInput"/>
</td>
</tr>
<tr>
<td>Adon Matsui</td>
<td>
<input type="text" value="red" class="favoriteColorInput"/>
</td>
</tr>
<tr>
<td>Robert Carlos</td>
<td>
<input type="text" value="Green" class="favoriteColorInput"/>
</td>
</tr>
<tr>
<td>Ronaldo Luis</td>
<td>
<input type="text" value="Green" class="favoriteColorInput"/>
</td>
</tr>
</table>
</div>
When I execute the code below it returns successfully with this string:
"table = "Name Favorite Color\r\nKen Master\r\nAdon Matsui\r\nRobert Carlos\r\nRonaldo Luis"
string table = webDriver.FindElement(By.XPath("/html/body/div[2]/div[2]/table")).Text;
But when I try to get cell value based on row and column, it throws exception as mentioned above. And here is the code to call to get cell value.
string cellVal = webDriver.FindElement(By.XPath("html/body/div[2]/div[2]/table/tr[1]/td[0]")).Text;
So I wonder am I missing something?
thanks.
Update:
string cellVal = webDriver.FindElement(By.XPath("/html/body/div[2]/div[2]/table/tr[1]/td[0]")).Text;
Solved:
With Chrome XPath helper, somehow it adds tbody in there which I don't have it in my HTML page, but after using it, it works.
Thank you everyone for helping. Very appreciate.
The issue caused by td[0], in xpath, index start with 1 not 0, so change you xpath to /html/body/div[2]/div[2]/table/tr[1]/td[1]

Fill control with another MVC

I have experience in C#, but don't have any in Javascript.
What I want to achieve shouldn't be that hard, but I just can't get it to work:
I want to fill the text property of a label with the text property of a textbox.
This needs to be done at the KeyUpEvent.
I already created the KeyUpEvent and it is working, but it doesn't fill my label's text property using the following code:
<script type="text/javascript">
$(document).ready(function ()
{
$("##Html.FieldIdFor(model => model.Quantity)").keyup(OnQuantityChanged);
});
function OnQuantityChanged()
{
alert("onQuantityChanged event fired.")
document.getElementById('##Html.FieldIdFor(model => model.SubTotalExclTax)').value = document.getelementById('##Html.FieldIdFor(model => model.UnitPriceExclTax)').value
}
</script>
So I create a function called OnQuantityChanged() and I call this function on KeyUp event.
The alert in my function: alert("onQuantityChanged event fired.") gets called and shows me a dialog, so the function does get called.
I'm using #Html.FieldIdFor, for getting the id of the control. I think this is implemented by NopCommerce and down here is the definition of the FieldIdFor method:
public static string FieldIdFor<T, TResult>(this HtmlHelper<T> html, Expression<Func<T, TResult>> expression)
{
var id = html.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
// because "[" and "]" aren't replaced with "_" in GetFullHtmlFieldId
return id.Replace('[', '_').Replace(']', '_');
}
I think I made a syntax error, but don't know how to debug Javascript, since setting a breakpoint in Visual Studio(2012), doesn't pause the code.
I think the line below has some incorrect syntax, correct me if i'm wrong:
document.getElementById('##Html.FieldIdFor(model => model.SubTotalExclTax)').value = document.getelementById('##Html.FieldIdFor(model => model.UnitPriceExclTax)').value
Update
HTML of page is below:
<table>
<tr>
<td>
#Html.NopLabelFor(model => model.UnitPriceInclTax):
</td>
<td>
#Html.EditorFor(model => model.UnitPriceInclTax)#Model.UnitPriceInclTax
</td>
</tr>
<tr>
<td>
#Html.NopLabelFor(model => model.UnitPriceExclTax):
</td>
<td>
#Html.EditorFor(model => model.UnitPriceExclTax)#Model.UnitPriceExclTax
</td>
</tr>
<tr>
<td>
#Html.NopLabelFor(model => model.Quantity):
</td>
<td colspan="2">
#Html.EditorFor(model => model.Quantity, new { id = "lblQuantity"})
</td>
</tr>
<tr>
<td>
#Html.NopLabelFor(model => model.SubTotalInclTax):
</td>
<td>
#Html.EditorFor(model => model.SubTotalInclTax)#Model.SubTotalInclTax
</td>
</tr>
<tr>
<td>
#Html.NopLabelFor(model => model.SubTotalExclTax):
</td>
<td>
#Html.EditorFor(model => model.SubTotalExclTax)#Model.SubTotalExclTax
</td>
</tr>
</table>
You don't need # when using document.getElementById just string representing id is enough.
There is no value of a label you could just set innerText property.
Pure javascript solution:
document.getElementById("YourID").innerText = "New Text";
JQuery Solution
$("#YourID").text("New Text");
That part of server side code is not executed by ASP.NET since it is inside a string. You can resole using a variable to store the id:
var subTotalId = #Html.FieldIdFor(model => model.SubTotalExclTax);
and then use the subTotalId in your javascript (given that Html.FieldIdFor return the id of the element.
A better way is to use only javascript, with ASP.NET MVC you should know the ids of the DOM elements, so why do you need to find them at runtime?
Why not using Jquery:
$('#IdOfSubTotalElement').val();

Retrieve element within html hierarchy

I have this piece of html code. I want to get the text inside the <div> tag using WatiN. The C# code is below, but I'm pretty sure it could be done way better than my solution. Any suggestions?
HTML:
<table id="someId" cellspacing="0" border="1" style="border-collapse:collapse;" rules="all">
<tbody>
<tr>
<th scope="col"> </th>
</tr>
<tr>
<td>
<div>Some text</div>
</td>
</tr>
</tbody>
</table>
C#
// Get the table ElementContainer
IElementContainer diagnosisElementContainer = (IElementContainer)_control.GetElementById("someId");
// Get the tbody element
IElementContainer tbodyElementContainer = (IElementContainer)diagnosisElementContainer.ChildrenWithTag("tbody");
// Get the <tr> children
ElementCollection trElementContainer = tbodyElementContainer.ChildrenWithTag("tr");
// Get the <td> child of the last <tr>
IElementContainer tdElementContainer = (IElementContainer)trElementContainer.ElementAt<Element>(trElementContainer.Count - 1);
// Get the <div> element inside the <td>
Element divElement = tdElementContainer.Divs[0];
Based on the given, something like this is how I'd go for IE.
IE myIE = new IE();
myIE.GoTo("[theurl]");
string theText = myIE.Table("someId").Divs[0].Text;
The above is working on WatiN 2.1, Win7, IE9.

Categories