What is preventing Javascript from execution? - javascript

Neither of the Javascript function is executed in "btnrepeat()", although I have called another javascript in page_load event and that is working fine
C#
protected void Button1_Click(object sender, EventArgs e)
{
Timer1.Enabled = true;
workerThread = new Thread(new ThreadStart(btnrepeat));
workerThread.Start();
}
protected void btnrepeat()
{
ClientScript.RegisterClientScriptBlock(GetType(), "mys", "abcd()", true);
for (int i = 1; i <= filecount; i++)
{
string trnsfrpth = #"E:\\ProjectLocalPath\" + filename;
last_file++;
balance_load(filename, trnsfrpth);
Thread.Sleep(200);
}
ClientScript.RegisterClientScriptBlock(GetType(), "mytts", "abcd()", true);
//Label1.InnerHtml = last_file.ToString();
//This is not aspx label, but an HTML div
//this is possible actually but not working here
}
Javascript
function abcd() {
alert('hello');
}
Function is doing what it is supposed to, so there is no logical mistake.
And I've also tried,
ClientScript.RegisterStartupScript(GetType(), "mytts", "abcd()", true);
And The last 3 lines commented is another problem, it doesn't work...why ?

Related

Unable to read CefSharp Chromium console message

I have a WinForm application that using cefsharp web browser. From what I learnt about cefsharp, the events MouseDown, Click cannot trigger in WinForm. So I decided to use javascript to send a message to the console, and trigger ChromiumWebBrowser.ConsoleMessage event instead. But that did not work well. Did I mess up the javascript code or execute the code wrongly?
Here are the codes, please noted that UI.cs is a Form object. A panel object pn_Browser already created in the design view. What I tried to do is, click any element and send "success" to the console. Then the Background show the received message if the message in console.log is "success".
Background.cs
public ChromiumWebBrowser browser;
public Background()
{
browser = new ChromiumWebBrowser("https://www.google.com");
browser.ConsoleMessage += browser_ConsoleMessage;
browser.FrameLoadEnd += browser_FrameLoadEnd;
}
public void browser_ConsoleMessage(object sender, ConsoleMessageEventArgs e)
{
if (e.Message == "success")
{
System.Windows.Forms.MessageBox.Show("Received message.");
}
}
public void browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
Chromium.ExecuteScriptAsync("document.addEventListener(\"click\", function() {alert('Detect a click.');});");
}
UI.cs
public UI()
{
InitializeComponent();
Background background = new Background();
pn_Browser.Controls.Add(background.browser);
background.browser.JavascriptMessageReceived += browser_JavascriptMessageReceived;
background.browser.ExecuteScriptAsyncWhenPageLoaded(
"function test() {console.log(\"success\")}" +
"document.addEventListener(\"click\", test);"
);
}
delegate void JavascriptReceivedCallback(object sender, JavascriptMessageReceivedEventArgs e);
private void browser_JavascriptMessageReceived(object sender, JavascriptMessageReceivedEventArgs e)
{
if (InvokeRequired)
{
JavascriptReceivedCallback callback = new JavascriptReceivedCallback(Browser_JavascriptMessageReceived);
Invoke(callback, new object[] { sender, e };
}
else
{
MessageBox.Show(e.Message.ToString());
}
}

OnServerClick with dynamic anchorlink not firing

I'm trying to fire an OnServerClick event from some anchor tag created dynamically. My event isn't firing from my anchor tag. i have no error.
Can someone help me ?
HtmlAnchor btn_close = new HtmlAnchor();
btn_close.Attributes.Add("class", "close");
btn_close.Attributes.Add("data-dismiss", "alert");
btn_close.Attributes.Add("aria-label", "Ne plus afficher");
btn_close.Attributes.Add("title", "Ne plus afficher");
btn_close.Attributes.Add("runat", "server");
btn_close.ServerClick += new EventHandler(hideNotificationBtn_Click);
btn_close.ID = notificationSent.NotificationSentID.ToString();
btn_close.InnerText = "test";
div_alert.Controls.Add(btn_close);
protected void hideNotificationBtn_Click(object sender, EventArgs e)
{
HtmlAnchor cb = (HtmlAnchor)sender;
int test = int.Parse(cb.Name);
NotificationSent.SetNotificationAsHidden(int.Parse(cb.Name));
}
My hide notification isn't fired from by anchor when i click on it.
I already tried to change it to a button.
Thank you for your help.
Anchors don't call server side functions even when they are runat server, however there is the LinkButton class that can be used instead. Ultimately it is rendered as JavaScript initiated postback. Check out https://forums.asp.net/p/1519048/3644158.aspx for more information.
Make sure you are creating that button early enough in the page lifecycle. Look to get it created OnInit of the Page.
This is because the event handling events happen after Page Init. Of course, the button has to have been created before the events can be detected on
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["falg"] != null)
{
Create();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Create();
ViewState.Add("falg", true);
}
void BtnServices_Click(object sender, EventArgs e)
{
Response.Write("hi");
}
void BtnServices_Command(object sender, CommandEventArgs e)
{
Response.Write("hi");
}
void Create()
{
BtnServices = new Button();
BtnServices.ID = "BtnServices";
BtnServices.Text = "Click Me";
BtnServices.Click += new EventHandler(BtnServices_Click);
BtnServices.Command += new CommandEventHandler(BtnServices_Command);
form1.Controls.Add(BtnServices);
}
Easier and reliable way to do this could be , instead of dynamically
adding the control, always add it, but set Visible=false initially.
Then where you're currently adding it, instead just make it visible.

How to add dynamic controls with different ID and having a different Click event in asp.net on a button click?

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["i"] = 1;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int i = (int)ViewState["i"];
Button MyButton = new Button();
MyButton.ID = "MyButton" + i;
divContainer.Controls.Add(MyButton);
i++;
ViewState["i"] = i;
}
Whenever i click on button to add a new control in a div with id="descriptionBox", then last created control gets deleted from that div and new control gets created instead.I want to create a new control on every click And add them into that div.
As you are using Asp controls, it renders at server side
every time you add control it refreshes the page and previous content goes away
you can use Page_PreInit event
protected void Page_PreInit(object sender, EventArgs e)
{
Request.Form.AllKeys.Where(key => key.Contains("button name")).ToList();
}
event to retain or re-Create the existing control
for more information have a look on the link https://www.aspsnippets.com/Articles/ASPNet-Dynamic-Controls-ViewState-Retain-state-for-dynamically-created-controls-on-PostBack.aspx

Telerik ASP.Net RadGrid Add New Record Client Side Javascript Prevent Behavior

I am attaching an onClick event to the Add Record button on my RadGrid. Code as follows:
Code Behind
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridCommandItem)
{
LinkButton lnk = (LinkButton)e.Item.FindControl("InitInsertButton");
lnk.Attributes.Add("onClick", "testClick()");
}
}
Javascript
function testClick(){
// Perform some Client Side Validation
var validated = false;
if(!validated){
radalert('Validation Fail', 100, 100, 'Window', null, null);
// What to call here to prevent the RadGrid from going into Insert (Edit) mode??
//I tried return false; but that did not prevent the grid.
}
}
So on my JS call, after the alert window has been displayed and I closed it, the RadGrid still goes into edit mode.
I tried a variation of the following:
Code Behind
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if(e.CommandName == RadGrid.InitInsertCommandName)
{
// If Validation Failed, prevent Radgrid from going to Edit Mode.
RadGrid1..MasterTableView.ClearEditItems();
}
}
Posting an answer so that for everyone who may stumble on this:
Code Behind:
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridCommandItem)
{
LinkButton lnk = (LinkButton)e.Item.FindControl("InitInsertButton");
lnk.Attributes.Add("onClick", "return testClick()");
}
}
Javascript
function testClick(){
// Perform some Client Side Validation
var validated = false;
if(!validated){
radalert('Validation Fail', 100, 100, 'Window', null, null);
return false;
}
}

How can i call javascript function from backend within updatepanel

How can I call javascript function from backend within updatepanel in asp.net.
ScriptManager.RegisterStartupScript(this,yourUpdatePanel.getType(),"Your js",true);
see http://msdn.microsoft.com/en-us/library/bb310408.aspx
Its not hard to do, but it's depends on you, how you can call a method/function,
1) without update panel
function welcome()
{
alert("Welcome Guys!");
}
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(Page.GetType(), "OnLoad", "welcome();", true);
}
2) With update panel
function welcome()
{
alert("Welcome Guys!");
}
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(Page, GetType(), "JsStatus","welcome();", true);
}
both are perfectly works ;)

Categories