Client script in Timer is not working - c#

I was just trying to learn some Asp.net Ajax stuff and calling javascript from my C# script.
I have a timer that triggers a method that calls a super simple javascript alert function.
It also updates the time every 10 seconds. Now it looks like my code should work. There are no build errors, no exceptions just it doesn't work. The C# part that updates the time. The javascript does not make the alert.
<%# Page Language="C#" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<script runat="server">
protected void Page_load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label1.Text = DateTime.Now.ToString();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
const string someScript = "alertMe";
Label1.Text = DateTime.Now.ToString();
ClientScript.RegisterStartupScript(this.GetType(),someScript, "alert('I was called from Content page!')", true);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server"> </asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="Label1"></asp:Label>
<asp:Timer ID="Timer1" runat="server" Interval="10000" OnTick ="Timer1_Tick"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

You need to use ScriptManager instead of ClientScript when you are putting the element that triggers the postback inside an UpdatePanel.
Change your code to:
ScriptManager.RegisterStartupScript(this,this.GetType(), someScript, #"alert('I was called from Content page!');", true);

You forgot a ;
ClientScript.RegisterStartupScript(this.GetType(),someScript, "alert('I was called from Content page!');", true);
Most browsers have an error console of some type that you can see these issues as they occur.

Related

C# asp.net WebForm add JS and run it from code behind

I have this WebForm Html:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="GetLink.aspx.cs" Inherits="GetLink" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="hidden" runat="server" id="hdnVal" value="55"/>
</div>
</form>
</body>
</html>
And i want to add to this code a JavaScript function and run it with this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("key1"))
{
ClientScript.RegisterStartupScript(GetType(), "key1", #"<script type=""text/javascript"">function callMyJSFunction() { document.getElementById(""hdnVal"").value='5'; }</script>");
}
ClientScript.RegisterStartupScript(this.GetType(), "key1", "<script>callMyJSFunction();</script>");
string resutOfExecuteJavaScript = hdnVal.Value;
}
When i run it the value of hdnVal keep the 55 value and not change. Any idea what is the problem?
Your code in Page_Load event should call ClientScript.RegisterClientScriptBlock when registering the JavaScript function of callMyJSFunction, whereas in your code you are registering this function as a startup script. This is the only mistake in your code.
So, if you change your server-side code to as below, then it will work according to your expectations.
protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsClientScriptBlockRegistered("key1"))
{
//register your javascript function
ClientScript.RegisterClientScriptBlock(GetType(), "key1", #"<script type=""text/javascript"">function callMyJSFunction() { document.getElementById(""hdnVal"").value='5'; }</script>");
}
ClientScript.RegisterStartupScript(this.GetType(), "key1", "<script>callMyJSFunction();</script>");
string resutOfExecuteJavaScript = hdnVal.Value;
}
The first problem is you are creating function in Clientscript while you can simply put the function in javascript and then just do the calling part.Second problem is that the time your function is calling that hiddenfield for view its not available on document simply means stop putting your code on page load and use a button click event instead.Third problem is you are using multiple inverted commas at so many places which aren't required.
This worked for me
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('document').ready()
{
function callMyJSFunction()
{
debugger;
document.getElementById('hdnVal').value = '5';
alert(document.getElementById('hdnVal').value);
}
// - including fonts, images, etc.
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="hidden" runat="server" id="hdnVal" value="55"/>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
and on cs page
protected void Button1_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "key1", "<script>callMyJSFunction()</script>",false);
string resutOfExecuteJavaScript = hdnVal.Value;
}

How do I write code to a button which must fire on both events onclick and onclientclick simultaneously with single click

iam writing code for button onclient event with js to print the webpage and onclick event for generating pdf and downloading it ..both must be done in a single action..
but when i cancel print which i onclient click event then oncick event is firing .
<script type="text/javascript">
function PrintPage()
{
window.print();
return true;
}
<asp:Button ID="Button3" runat="server" Text="PTPDF" UseSubmitBehavior="false" OnClick="Button3_Click1" OnClientClick ="javascript:PrintPage();" />
</div>
protected void Button3_Click1(object sender, EventArgs e)
{//here is the code for pdf generation,
this code must get fired automatically after onclient click event without users action}
Below code works perfectly on my end and illustrateson how both OnClick and OnClientClick works at a same time-
ASPX -
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Click.aspx.cs" Inherits="Click" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function confirmthis()
{
document.getElementById('TextBox2').value = 'onclient works';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" OnClientClick="return confirmthis();" Text="Click Me" /></div>
</div>
</form>
</body>
</html>
Inline code -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Click : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "OnClick works";
}
}
Please paste the above code at your end and let me know if it still doesn't work.
Thanks!!

asp.net display textbox on item checked

So just starting out with asp.net... I want to display my textbox when my checkbox is checked, but this doesn't seem to be working. I also tried with the visible property, but that didn't work either. What am I doing wrong exactly?
Code:
protected void checked_CheckedChanged(object sender, EventArgs e)
{
text.Style["display"] = "block";
}
Layout:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<p>gehuwd/samenwonend<asp:checkbox runat="server" ID="checked" OnCheckedChanged="checked_CheckedChanged"></asp:checkbox>
</p>
<asp:TextBox runat="server" ID="text" style="display:none"></asp:TextBox>
</form>
</body>
</html>
Use the AutoPostBack property for checkbox and set it to true:
<asp:checkbox runat="server" ID="checked" OnCheckedChanged="checked_CheckedChanged" AutoPostBack="true"></asp:checkbox>
You can use add css property of textbox in c# as given below. If your checkbox OnCheckedChanged is not working then you can set property AutoPostBack is true in checkbox.
protected void checked_CheckedChanged(object sender, EventArgs e)
{
text.Attributes.Add("display","block");
}
You can also do this completely client side, using jQuery or javascript.Making a post back to the server everytime you need to change the visual appearance of your HTML can put unnecessary strain on the server and have a negative effect on the user experience by slowing down the overall performance of your site.
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var id = "<%: text.ClientID %>";
id = "#" + id;
$(id).hide();
$("#chkShowHide").change(function () {
if (this.checked) {
$(id).show();
}
else{
$(id).hide();
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<input id="chkShowHide" type="checkbox" /> Show\Hide<br />
<asp:TextBox runat="server" ID="text"></asp:TextBox>
</form>
</body>

ASPX Postback selectedIndexChanged

I am using an combobox with some values and AutoPostBack = true, the page does not refresh.
I have a selectedIndexChanged event as well.
I managed to get the selectedValue and I would like to show this in a TextBox.
In the selectedIndexChanged event I did:
textBox1.Text = selectedValue.ToString();
When I inspect this textbox element with Google Chrome I can see the value is set in the TextBox.
But in the browser the value isn't shown, still an empty TextBox.
Do you guys have any clue why this could happen?
Thanks!
How do you populate items for ComboBox? If dynamically via On-Load event then make sure that method that adds items does not run on PostBack.
Here is your working code buddy.
Don't forget ToString method.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test2.aspx.cs" Inherits="Test2" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<asp:ComboBox ID="ComboBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ComboBox1_SelectedIndexChanged">
<asp:ListItem>Item1</asp:ListItem>
<asp:ListItem>Item2</asp:ListItem>
<asp:ListItem>Item3</asp:ListItem>
</asp:ComboBox>
<asp:TextBox runat="server" ID="textBox1"/>
</div>
</form>
</body>
</html>
and code
public partial class Test2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = ComboBox1.SelectedValue.ToString();
}
}

ScriptManager.RegisterStartupScript not triggered second time inside updatepanel

My aspx page
<span>
<asp:UpdatePanel ID="upPlayBtn" runat="server" >
<ContentTemplate>
<asp:Button runat="server" id="btn" Text="Play" OnClick="btnPlay" />
</ContentTemplate>
</asp:UpdatePanel>
</span>
<script type="text/javascript">
function OpenPlayerWindow() {
OpenPlayWindow("<%=PlayLink%>");
}
function OpenPlayerWindowForError() {
alert("Please check after sometime. Thanks!")
}
</script>
My CS page
protected void btnPlay(object sender, EventArgs e)
{
if(condition)
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(),"tabs", "OpenPlayerWindow();", true);
}
else
{
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindowForError();", true);
}
}
When I click the "Play" button for first time, OpenPlayerWindow() or OpenPlayerWindowForError() opens accoding to the condition. And if I click the button again, "btnPlay" is called but not any of JS function.
If I refresh the page, it works perfect again.
<span>
<asp:UpdatePanel ID="upPlayBtn" runat="server" >
<ContentTemplate>
<asp:Button runat="server" id="btn" Text="Play" OnClick="btnPlay" />
<script type="text/javascript">
function OpenPlayerWindow() {
OpenPlayWindow("<%=PlayLink%>");
}
function OpenPlayerWindowForError() {
alert("Please check after sometime. Thanks!")
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
</span>
I am not able to write this code in comments hence I am writing this as an answer. The following is the code which I have with me. Please copy-paste it in a separate project and try if it works.
Also if I am not replicating this issue properly(not written the code correctly) then please comment.
If the code is okay with you and if it works on a separate project then there probably is a problem in some other code which is not shown in your question.
aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Practice_Web.WebForm2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<div>
<span>
<asp:UpdatePanel ID="upPlayBtn" runat="server">
<ContentTemplate>
<asp:Button runat="server" ID="btn" Text="Play" OnClick="btnPlay" />
</ContentTemplate>
</asp:UpdatePanel>
</span>
<%--It works if I keep the script here also--%>
</div>
</form>
</body>
<script type="text/javascript">
function OpenPlayerWindow() {
alert("Thanks!");
}
function OpenPlayerWindowForError() {
alert("Please check after sometime. Thanks!");
}
</script>
</html>
aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Practice_Web
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//This is just to simulate the condition part of the original code
if (Session["condition"] == null)
Session["condition"] = false;
else
Session["condition"] = !Convert.ToBoolean(Session["condition"]);
}
protected void btnPlay(object sender, EventArgs e)
{
bool condition = Convert.ToBoolean(Session["condition"]);
if (condition)
{
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindow();", true);
}
else
{
ScriptManager.RegisterStartupScript(upPlayBtn, upPlayBtn.GetType(), "tabs", "OpenPlayerWindowForError();", true);
}
}
}
}
try below code
protected void btnPlay(object sender, EventArgs e)
{
if(condition)
ScriptManager.RegisterStartupScript(this, GetType(),"tabs", "OpenPlayerWindow();", true);
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "tabs", "OpenPlayerWindowForError();", true);
}
}

Categories