String from codebehind to array in Javascript - c#

Hi all i have code that reads from a DB and populates a string in the code behind
List<string> rows = new List<string>();
DataTable prods = common.GetDataTable("vStoreProduct", new string[] { "stpt_Name" }, "stpt_CompanyId = " + company.CompanyId.ToString() + " AND stpt_Deleted is null");
foreach (DataRow row in prods.Rows)
{
prodNames += "\"" + row["stpt_Name"].ToString().Trim() + "\",";
}
string cleanedNanes = prodNames.Substring(0, prodNames.Length - 1);
prodNames = "[" + cleanedNanes + "]";
This produces something like ["Test1","Test2"]
In javascript i have
var availableTags = '<% =prodNames %>';
alert(availableTags);
How can i access this like an array in javascript like
alert(availableTags[5]);
and get the full item at the given index.
Thanks any help would be great

Get rid of the quotes:
var availableTags = <% =prodNames %>;
With the quotes there, you're creating a JavaScript string. Without them, you've got a JavaScript array constant.

You're going to have to split the variable from .NET into a JS array.
Check out: http://www.w3schools.com/jsref/jsref_split.asp
Example based on your code:
var availableTags = '<% =prodNames %>';
var mySplitResult = availableTags .split(",");
alert(mySplitResult[1]);

I believe split() will do what you want:
var availableTagsResult = availableTags.split(",");
alert(availableTagsResult[1]) //Display element 1
This will create an array from the string which has been split on ,

Related

Extract value from input element string array

i have an string array read from <td> of a datatable like this
"<input id=\"item_Job_ID\" name=\"item.Job_ID\" type=\"text\" value=\"5036\">"
how can i get only the value from it in c#.
i tried Split("\\") which doesn't work. can i use linq to extract the value ?
Thank You in Advance
I think, It's work for you
string inputstr = "< input id =\"item_Job_ID\" name=\"item.Job_ID\" type=\"text\" value=\"5036\">";
var splitdataList = inputstr.Split(new string[] { "\"", "=", " " }, StringSplitOptions.RemoveEmptyEntries).ToList();
var value = splitdataList.Contains("value") ? splitdataList[splitdataList.IndexOf("value") + 1] : ""; // Return 5036
use Html Agility Pack.
HtmlDocument doc = new HtmlDocument();
string htmlContent = "<input id=\"item_Job_ID\" name=\"item.Job_ID\" type=\"text\" value=\"5036\">";
doc.LoadHtml(htmlContent);
HtmlNode inputNode = doc.DocumentNode.FirstChild;
string value = inputNode.GetAttributeValue("value", "0");

My function to get text between two strings isn't finding the correct words

I am creating an application that fetches information about a website. I have been trying several approaches on getting the information from the HTML tags. The website is who.is and I am trying to get information about Google (as a test!) Source can be found on view-source:https://who.is/whois/google.com/ < (if using Chrome browser)
Now the problem is that I am trying to get the name of the creator of the website (Mark or something) but I am not receiving the correct result. My code:
//GET name
string getName = source;
string nameBegin = "<div class=\"col-md-4 queryResponseBodyKey\">Name</div><div class=\"col-md-8 queryResponseBodyValue\">";
string nameEnd = "</div>";
int nameStart = getName.IndexOf(nameBegin) + nameBegin.Length;
int nameIntEnd = getName.IndexOf(nameEnd, nameStart);
string creatorName = getName.Substring(nameStart, nameIntEnd - nameStart);
lb_name.Text = creatorName;
(source contains html of page)
This doesn't put out the correct answer though... I think it has something to do with the fact that I use a [\] because of the multiple "" 's...
What am I doing wrong? :(
Instead of trying the parse the html result manually, use a real html parser like HtmlAgilityPack
using (var client = new HttpClient())
{
var html = await client.GetStringAsync("https://who.is/whois/google.com/");
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var nodes = doc.DocumentNode.SelectNodes("//*[#class='col-md-4 queryResponseBodyKey']");
var results = nodes.ToDictionary(n=>n.InnerText, n=>n.NextSibling.NextSibling.InnerText);
//print
foreach(var kv in results)
{
Console.WriteLine(kv.Key + " => " + kv.Value);
}
}
string getName = "<div class=\"col-md-4 queryResponseBodyKey\">Name</div><div class=\"col-md-8 queryResponseBodyValue\">";
string nameBegin = "<div class=\"col-md-4 queryResponseBodyKey\">";
string nameEnd = "</div>";
int nameStart = getName.IndexOf(nameBegin) + nameBegin.Length;
int nameIntEnd = getName.IndexOf(nameEnd, nameStart);
string creatorName = getName.Substring(nameStart, nameIntEnd - nameStart);
//lb_name.Text = creatorName;
Console.WriteLine(creatorName);
Console.ReadLine();
Is this what you are looking for, to get Name from that div ?

Regex, Remove function in a string

I'm trying to get the function DoDialogwizardWithArguments that is inside a string using Regex:
string:
var a = 1 + 2;DoDialogWizardWithArguments('CopyGroup', '&act=enviarcliente', 96487, (Q.getBody().$.innerWidth()/4)*3, Q.getBody().$.innerHeight(), new Function("if(localStorage.getItem('atualizaPgsParaCli')){{Q.window.close();Q.window.proxy.reload();}}localStorage.removeItem('atualizaPgsParaCli');return true;"), false);p = q.getBOdy();
actual Regex (pattern):
DoDialogWizardWithArguments\((.*\$?)\)
Result expected:
DoDialogWizardWithArguments('CopyGroup', '&act=enviarcliente', 96487, (Q.getBody().$.innerWidth()/4)*3, Q.getBody().$.innerHeight(), new Function("if(localStorage.getItem('atualizaPgsParaCli')){{Q.window.close();Q.window.proxy.reload();}}localStorage.removeItem('atualizaPgsParaCli');return true;"), false)
The problem:
If there's another parentheses ")" that is not the parentheses of DoDialogWizardWithArguments function the Regex is getting this too.
How can i get only the function with his open and close parentheses.
If Regex is not possible, whats the better option?
Example regex link:https://regex101.com/r/kP2bQ4/1
Try this one as regex: https://regex101.com/r/kP2bQ4/2
DoDialogWizardWithArguments\(((?:[^()]|\((?1)\))*+)\)
I'd probably try to simplify it like this:
var str = #"var a = 1 + 2;DoDialogWizardWithArguments('CopyGroup', '&act=enviarcliente', 96487, (Q.getBody().$.innerWidth()/4)*3, Q.getBody().$.innerHeight(), new Function("if(localStorage.getItem('atualizaPgsParaCli')){{Q.window.close();Q.window.proxy.reload();}}localStorage.removeItem('atualizaPgsParaCli');return true;"), false);p = q.getBOdy();"
var lines = str.Split(';');
foreach(var line in lines)
{
if(line.Contains("DoDialogWizardWithArguments")){
int startPos = line.IndexOf("(");
int endPos = line.IndexOf(")");
return line.Substring(startPos+1, endPos - startPos - 1);
}
}
return "Not found";
If you don't want to detect if DoDialogWizardWithArguments was correctly written but just the function itself, try with "DoDialogWizardWithArguments([^,],[^,],[^,],([^,]),.+);".
Example:
String src = #"xdasadsdDoDialogWizardWithArguments('CopyGroup', '&act=enviarcliente', 96487, (Q.getBody().$.innerWidth()/4)*3, Q.getBody().$.innerHeight(), new Function(" + "\""
+ "if(localStorage.getItem('atualizaPgsParaCli')){{Q.window.close();Q.window.proxy.reload();}}localStorage.removeItem('atualizaPgsParaCli');return true;"
+ "\"" + "), false);p"; //An example of what you asked for
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(#"DoDialogWizardWithArguments([^,]*,[^,]*,[^,]*,([^,]*),.+);"); //This is your function
MessageBox.Show(r.Match(src).Value);
if (r.IsMatch(src))
MessageBox.Show("Yeah, it's DoDialog");
else MessageBox.Show("Nope, Nope, Nope");

I want to split the data in the list when i see the ; in C#

I need to split this data in the box to and add it to new line when it see the ";"
var retryParamInfo = new ExParamsContent
{
Idenitifier = tempIdentifier.SerialNumber,
Name = String.Format( "Retry Information Console {0}",i),
Value = MyTestRunGlobals.FixtureComponents[i].Uuts[0].RetryList,
//Value = thisUut.RetryList.Replace("\n", "\n" + Environment.NewLine),
};
uutTempInfo.ExParams.Add(retryParamInfo);
To split a string when some character occours, you can use:
myString.split(';');
and make the result of this be inside a array.

What's wrong with my JavaScript? (C#/ASP.NET)

Here is my JavaScript:
<script type="text/javascript">
function onholdev(index) {
var chk = document.getElementById('<%=grdCons.Rows[' + index + '].FindControl("chkHold").ClientID %>');
var txt = document.getElementById('<%=grdCons.Rows[' + index + '].FindControl("txtReason").ClientID %>');
if (chk.checked == true) {
txt.disabled = false;
}
else {
txt.disabled = true;
txt.value = "";
}
}
</script>
The 'index' variable comes from the RowDataBound event of my GridView, like so:
CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
chkHold.Attributes.Add("onchange", "onholdev(" + e.Row.RowIndex + ")");
However, I'm getting 'too many characters in string literal' in the first line of my function (beginning with var chk). Why is this?
You're mixing client and server-side script...you just can't do this. This is executed server-side:
grdCons.Rows[' + index + '].FindControl("chkHold").ClientID
But you're calling it client-side and trying to pass an ID, that's just not something you can do, look at your rendered JavaScript function and this will be much clearer. Instead just use the ID of the table, then you can find your controls that way, for example:
var row = document.getElementById("grdCons").rows[index];
var inputs = row.getElementsByTagName("input");
//then filter by ID match, class, whatever's easiest and set what you need here
That's probably because ASP.NET throws an error, which is written in the client side call of getElementById. The onholdev function is executed client - side, and so cannot pass the index parameter to ASP.NET which is executed server - side. Try this:
<script type="text/javascript">
function onholdev(checkbox, textbox) {
var chk = document.getElementById(checkbox);
var txt = document.getElementById(textbox);
if (chk.checked == true) {
txt.disabled = false;
}
else {
txt.disabled = true;
txt.value = "";
}
}
</script>
Replacing your server - side code with this:
CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
chkHold.Attributes.Add("onchange", "onholdev('" +
e.Row.FindControl("chkHold").ClientID + "','" +
e.Row.FindControl("txtReason").ClientID + "')");
The problem is your use of the single quote characters in ' + index + '. Change those to double qoutes and it should work.

Categories