declaring div in c# with onclick event - c#

i m trying to create a div container in c# codebehind.i want the div container to raise a javascript event onclick once its clicked.its working fine.below is the code where a javascript function "ds()" is called with no parameters.the problem is that i want to pass a parameter to javascript function.I dont know how to accomplish it.Kindly facilitate me.
//string userIcon = "gbn";
sb.Append(userIcon + #"<div onclick=""ds()"" style='background-color: #EFEFEF; padding: 10px;'>" + "<a href=#>" + "MubbshirAbbs" + "</a></div><br>");
Literal1.Text = sb.ToString();
The Javascript function is this:
function ds()
{
var a="";alert("123");
document.getElementById("TextBox1").style.backgroundColor="red";
}
Kindly let me know how can i add a parameter in the div onclick function.

Alter the C# code:
sb.Append(userIcon);
sb.Append(#"<div onclick=""ds(");
sb.Append("'clicked'");
sb.Append(#")"" style='background-color: #EFEFEF; padding: 10px;'>");
sb.Append("<a href=#>");
sb.Append("MubbshirAbbs");
sb.Append("</a></div><br>");
Alter the javascript:
function ds(param)
{
var a="";alert("123");
document.getElementById("TextBox1").style.backgroundColor="red";
}

I don't know if I get your problem, can't you just do this?:
sb.Append(userIcon + #"<div onclick=""ds(" + parameter + ")"" style='background-color: #EFEFEF; padding: 10px;'>" + "<a href=#>" + "MubbshirAbbs" + "</a></div><br>");
Literal1.Text = sb.ToString();
function ds(parameter)
{
var a="";alert(parameter);
document.getElementById("TextBox1").style.backgroundColor="red";
}

Related

Webview2 SetVirtualHostNameToFolderMapping not allowed to load local resource

Hey all I am using the new WebView2 with my WinForms app. I can get it to display my dynamic html that I create but it has the "" when it tries to load the images for the page.
The image tag looks like this:
<div id="animation1" style="display: inline-flex;">
<img src="file:///C:\Users\admin\source\repos\wCondictions\bin\x86\Debug\Resources/nice.gif" style="height: 110px; width: 110px;">
<span class="imgWeather">Nice</span>
</div>
The code I am currently using is this:
fileNames = new DirectoryInfo(resourcePath)
.GetFiles()
.OrderBy(p => Path.GetFileNameWithoutExtension(p.Name))
.Select(fi => fi.Name)
.ToArray();
string blah = Path.Combine(Application.StartupPath, "Resources");
string fullHtml = string.Empty;
string HeaderHtml = "<!DOCTYPE html>\n" +
"<html>\n" +
"<style>\n" +
".imgW {\n" +
"position: absolute;\n" +
"z-index: 10;\n" +
"color: red;\n" +
"width: 110px;\n" +
"height:30px;\n" +
"text-align: center;\n" +
"vertical-align: middle;\n" +
"top: 88px;\n" +
"background-color: aquamarine;\n" +
"font-family: Arial;\n" +
"font-size: small;\n" +
"}\n" +
"</style>\n" +
"<body style=\"background-color: #00000;\">";
string dynamixImg = "<div id=\"animation1\" style=\"display: inline-flex;\">\n" +
"<img src=\"file:///" + blah + "/{0}\" style=\"height: 110px; width: 110px;\" />\n" +
"<span class=\"imgW\">{1}</span>\n" +
"</div>";
string FooterHtml = "</body>" +
"</html>";
for (int a = 0; a < fileNames.Count(); a++)
{
fullHtml += string.Format(
dynamixImg,
fileNames[a],
fileNames[a]
.Replace(".gif", "")
.Replace("&", "&&")
) + "\n";
}
await webView21.EnsureCoreWebView2Async();
webView21.CoreWebView2.SetVirtualHostNameToFolderMapping(
"Resources",
#"C:\Users\admin\source\repos\wCondictions\bin\x86\Debug\Resources\",
CoreWebView2HostResourceAccessKind.Allow
);
webView21.NavigateToString(HeaderHtml + fullHtml + FooterHtml);
I've seen many places where it says to use the SetVirtualHostNameToFolderMapping but even with that it still says the same error.
So I am not sure what I am missing or misunderstanding about how to use the SetVirtualHostNameToFolderMapping in order to allow the images to load locally?
Ok, I will try again, my first answer was confusing.
You get the error because you use the file:// protocol.
It seems you have not fully understood the the use of SetVirtualHostNameToFolderMapping.
Once you have set the virtual server by calling SetVirtualHostNameToFolderMapping you should use that virtual server just as you use any other server on the internet. Do NOT use file://!
So all you have to do is edit your HeaderHtml and your <img src.
The HeaderHtml should include a <base> tag, which should point to your virtual server root:
<html>
<head>
<base href="http://Resources" />
</head>
That makes it very easy to build you dynamic <ìmg> tags, the source is simply the file name:
<img src="image.png" />
Now WebView2will translate it into a file path and fetch the image!
As a side note, you can also include files from sub-folder by adding the folder name in front of the file name, like this:
<img src="/subfolder/image.png" />

How to get a value from a javascript file to c#?

I'm using ASP.NET to make a website for a hotel and at this point to show the hotel rooms I've created a javacript file to generate div's, now I want to get the value of the room number that by clicking "learn more "transfer the value of the number of the room to the other page
I already tried to use cookies but it does not work
here's the js file that generates the div:
$(document).ready(function () {
$.get('http://localhost/quartos.php', function (data) {
var results = JSON.parse(data);
console.log(results);
for (i = 0; i < results.length; i++) {
var div = "<div class='col-sm col-md-6' height='600px' width='400px'><div class='room'><a href='' class='img d-flex justify-content-center align-items-center' style='background-image: url(images/Quartos/" + results[i].imagem + ");'></a><div class='text p-3 text-center><h3 class=' mb-3'><a href=''>Quarto " + results[i].descricao + "</a></h3 > <p><span class='price mr-20'>" + results[i].Preco_quarto + "\u20AC</span><asp:Label ID='Label1' runat='server' Text='ç aop'></asp:Label><span class='per'> por noite</span></p> <ul class='list'><li><span>Max:</span>" + results[i].Lotacao_Maxima + " Pessoas</li><li><span>Vista:</span>" + results[i].Vista + "</li></ul><hr><p class='pt-1'><button class='btn btn-primary' runat='server' onserverclick='btn_quartos'>Ver Detalhes<span class='icon-long-arrow-right'></button></span></p></div></div></div>";
document.cookie = "CookieName=" + results[i].Num_Quarto + ";";
$("#quartos").append(div);
}
});
});
and the cs of the "next" page:
protected void Page_Load(object sender, EventArgs e)
{
string num_quarto = Request.Cookies["CookieName"].Value.ToString();
}
You're overwriting the cookie to something new each time in the for loop, so the cookie is always going to hold the last result in results, despite what they select.
Although, using a cookie to pass info from one page to another isn't an ideal way to do what you want anyway.
A better way would be to make your "learn more" page able to accept a room number as a query string value.
Example: http://localhost/learnmore.php?cuarto=123
Then that looks up the room information and renders the information into the html.
In doing that, you can simplify the link in your div element to point to learmore.php?cuarto="+results[i].Num_Quarto and not have to repurpose the cookie functionality for a behavior it's not really meant for.

How to programmatically add span id= to an HTML document

I am currently looking at an example D3 visualization that creates gauges on screen. The current body looks like this:
<body onload="initialize()">
<span id="memoryGaugeContainer"></span>
<span id="cpuGaugeContainer"></span>
<span id="networkGaugeContainer"></span>
<span id="testGaugeContainer"></span>
</body>
In my C# application, I need to call a javascript function that will create a
<span id="id here"></span>
line in the body. My C# code looks as so:
webView.ExecuteJavascript("createSpan(" + Convert.ToString(this.application.Document.Properties["column"]).Replace(" ", "_") + aggregation.SelectedItem.ToString() + flColumn.SelectedItem.ToString().Replace(" ", "_") + "GaugeContainer" + ")");
What would my Javascript function be? My current attempt at the "createSpan" function is this:
function createSpan(id) {
var spanTag = document.createElement("span");
spanTag.id = id;
document.body.appendChild(spanTag);
}
The "executejavascript" function comes from Awesomium.
Am I doing this right?
Thanks

Dynamic javascript error

I'm trying to make a dynamic javascript from code behind that would be added to the page and would enable thus a little jwplayer to open up, my code so far:
void playAudioFile(string path)
{
string script =
#" var div = document.getElementById('playerDiv');
var audio = document.createElement('audio');
audio.setAttribute('id', 'audioPlayer');
div.appendChild(audio);
jwplayer(""audioPlayer"").setup({
file: 'http://ps.staging.be/webservice/MP3DownloadHandler.ashx?id='" + path +
#"'&date=' + '<%=Encrypt.EncryptString(String.Format(""{0:dd/MM/yyyy}"",
DateTime.UtcNow))%>',
width: ""100%"",
height: ""30"",
type: 'mp3',
stretching: ""uniform"",
controlbar: 'bottom'
});
";
//Add the script to it's tags
HtmlGenericControl playScript = new HtmlGenericControl("script");
playScript.InnerHtml = script;
//Add it on his place
playerDiv.Controls.Add(playScript);
But this turns out to a "could not make contact with localhost:55323 does anyone know what mistake I make? + is there a better way? The purpose would be to display a player if a person clicked on an element on my website, and the players path would change on hand of the selected item. I'm kinda making a system like youtube if you want something to compare with.
Final Solution
string date = Encrypt.EncryptString(String.Format("{0:dd/MM/yyyy}", DateTime.UtcNow));
string script =
#" var div = document.getElementById('ContentPlaceHolder1_playerDiv');
var audio = document.createElement('audio');
audio.setAttribute('id', 'audioPlayer');
div.appendChild(audio);
jwplayer(""audioPlayer"").setup({
file: 'http://ps.staging.be/webservice/MP3DownloadHandler.ashx?id=" + path + #"&date=" + date + #"',
width: '100%',
height: '30',
type: 'mp3',
stretching: 'uniform',
controlbar: 'bottom'
});
";
//Add the script to it's tags
HtmlGenericControl playScript = new HtmlGenericControl("script");
playScript.InnerHtml = script;
//Add it on his place
playerDiv.Controls.Add(playScript);
You should be using ClientScript.RegisterStartupScript to do this:
Page.ClientScript.RegisterStartupScript(this.GetType(), "FooKey", script, true);
You have a code block inside the script, not sure why you don't build that string in code and then append it to the script:
string date = Encrypt.EncryptString(String.Format("{0:dd/MM/yyyy}", DateTime.UtcNow));
string script =
#" var div = document.getElementById('playerDiv');
var audio = document.createElement('audio');
audio.setAttribute('id', 'audioPlayer');
div.appendChild(audio);
jwplayer(""audioPlayer"").setup({
file: 'http://ps.staging.be/webservice/MP3DownloadHandler.ashx?id='" + path + #"'&date=" + date + ", width: '100%', height: '30',type: 'mp3', stretching: 'uniform',controlbar: 'bottom'});";
You can not add scriptlet in the string and assign it to some controls InnerHtml.
I would write javascript directly to aspx (html) side as I belive that is simple and more straight forward.
Change
+ '<%=Encrypt.EncryptString(String.Format(""{0:dd/MM/yyyy}"", DateTime.UtcNow))%>',
To
+ Encrypt.EncryptString(String.Format("{0:dd/MM/yyyy}", DateTime.UtcNow))

ASP.NET - How to write some html in the page? With Response.Write?

I need that some html in the area in the asp.net page that i am coding, is changed according to a string variable.
I was thinking about creating a label, and then change the text on it.
But the string variable contains something like:
<h2><p>Notify:</p> alert</h2>
So, I don't feel that give this to a label text is a good idea
How i can do?
Using response.write?
If I use response.write, my added code will be at the beginning of the html source, how i can tell him to add it in a specific ?
Thank you
If you really don't want to use any server controls, you should put the Response.Write in the place you want the string to be written:
<body>
<% Response.Write(stringVariable); %>
</body>
A shorthand for this syntax is:
<body>
<%= stringVariable %>
</body>
why don't you give LiteralControl a try?
myLitCtrl.Text="<h2><p>Notify:</p> Alert</h2>";
If you want something lighter than a Label or other ASP.NET-specific server control you can just use a standard HTML DIV or SPAN and with runat="server", e.g.:
Markup:
<span runat="server" id="FooSpan"></span>
Code:
FooSpan.Text = "Foo";
ASPX file:
<h2><p>Notify:</p> <asp:Literal runat="server" ID="ltNotify" /></h2>
ASPX.CS file:
ltNotify.Text = "Alert!";
Use a literal control and write your html like this:
literal1.text = "<h2><p>Notify:</p> alert</h2>";
You should really use the Literal ASP.NET control for that.
You can go with the literal control of ASP.net or you can use panels or the purpose.
You can also use pageMethods in asp.net. So that you can call javascript functions from asp.net functions. E.g.
[WebMethod]
public static string showTxtbox(string name)
{
return showResult(name);
}
public static string showResult(string name)
{
Database databaseObj = new Database();
DataTable dtObj = databaseObj.getMatches(name);
string result = "<table border='1' cellspacing='2' cellpadding='2' >" +
"<tr>" +
"<td><b>Name</b></td>" +
"<td><b>Company Name</b></td>" +
"<td><b>Phone</b></td>"+
"</tr>";
for (int i = 0; i < dtObj.Rows.Count; i++)
{
result += "<tr> <td><a href=\"javascript:link('" + dtObj.Rows[i][0].ToString().Trim() + "','" +
dtObj.Rows[i][1].ToString().Trim() +"','"+dtObj.Rows[i][2]+ "');\">" + Convert.ToString(dtObj.Rows[i]["name"]) + "</td>" +
"<td>" + Convert.ToString(dtObj.Rows[i]["customerCompany"]) + "</td>" +
"<td>"+Convert.ToString(dtObj.Rows[i]["Phone"])+"</td>"+
"</tr>";
}
result += "</table>";
return result;
}
Here above code is written in .aspx.cs page. Database is another class. In showResult() function I've called javascript's link() function.
Result is displayed in the form of table.

Categories