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))
Related
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" />
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.
I have troubles with adding blocks with a specific attributes on my asp.net mvc project using jquery.
I need to add block into the page depending on what i have in a dropdownlist(created via c#)
I had created a hidden block in my view(view the code below) wich makes "select" tag with options from my "List"
<div id="other" class="EqItem">
<p>Else: #Html.DropDownList("else", Model.ModEq("",""))</p>
<p>Serial №: #Html.TextBox("serialelse")</p>
</div>
After loading the page i use a function which removes this block from DOM and makes the copy of html code of this block into a variable(blockToAdd )
function BlockDelete()
{
blockToAdd = $("#other").html();
$("#other").remove();
}
then i use this variable to dinamically add blocks into my page(the function below)
function ShowListEtc()
{
for (c = 0; c < 15; c++)
{
if (!$("#divotherlist" + c + "").length) {
id = "divotherlist" + c + "";
clas = "EqItem";
blockToAdd = blockToAdd.trim();
$(".rightside").append('<div id="' + id + '">' + blockToAdd
+ '<p><img id ="' + id + 'D"src="/Images/delete.png"
onclick="Delete(id)"></p></div>');
$("#" + id).attr('class', clas);
$("#"+id).show();
selectid = "othersel" + c;
$("#" + id).find("select").attr('id', selectid);
$('#' + selectid + ' option').each(function () {
this.setAttribute('id', TransL(this.text) + c);
this.setAttribute('onclick', 'MakeNameParent(id)')
});
break;
}
}
}
The point is that i try to change attributes within created block(append(') but they are not applying!
When i made the code first time, it worked, but suddenly it had stopped to work, then i tried to use .prepend instead of .append, it began to work for a while but after reopening the project, it had stopped to work again!
Please tell me what i've done incorrect!
Thank you!
Error: missing } in XML expression
source code: http://localhost:3811/Clinic/ScheduleModule/ManageWorkingTime.aspx?ScheduleId=FRXTn%2fX1N8Wy8C%2fdJqQmDjrOEECv%2fRwauMVX6ZTipAM%3d
line: 0, column: 188
code:
<script language='javascript'>$(document).ready(function() {Sexy.alert( "Can not copy files." );});</script>
CODE:
public static void ShowAsync(string sMessage, MessageBoxTypes sType, Control control, Page pPage)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script language='javascript'>");
string sMsg = sMessage;
sMsg = sMsg.Replace("\n", "\\n");
sMsg = sMsg.Replace("\"", "'");
sb.Append(#"$(document).ready(function() {");
sb.Append(#"Sexy." + sType + #"( """ + sMsg + #""" );");
sb.Append(#"});");
sb.Append(#"</" + "script>");
ScriptManager.RegisterClientScriptBlock(pPage, typeof(Page), control.ClientID, sb.ToString(), true);
}
if i change true to false in RegisterClientScriptBlock then i get
error: $ is not defined
source code: http://localhost:3811/Clinic/ScheduleModule/ManageWorkingTime.aspx?ScheduleId=dH0ry1kng6MwGCRgCxXg8N5nCncbzPzn3TAOEI0tAY4%3d
line: 0
i call this popup like:
MessageBox.ShowAsync("Can not copy files.", MessageBoxTypes.alert, this, Page);
What can be wrong. If i copy this (JQUERY)
<script language='javascript'>$(document).ready(function() {Sexy.alert( "Can not copy files." );});</script>
into some .aspx page popup works. But if i call it from code behind and daypilot pro in this updatepanel form then i get this error.
Can be problem that two ajax framewroks mixed themself? How to prevent this?
i try with jquery.noConflict but it is the same
$.noConflict();
jQuery(document).ready(function() { Sexy.alert("Can not copy files."); });
Thx
If you change the last parameter in RegisterClientScriptBlock from true to false it will not add the script tag anymore. Currently with the setting to true, you have the script tag twice. Not sure what happens, but can't be good :-)
$ sounds like jquery? You don't mention what you are using? I mix ASP.NET Ajax with jquery and that works fine. What Version are you on?
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";
}