LinkButton click doesn't trigger with no javascript - javascript

Web forms user control generating a LinkButton in PageInit:
LinkButton b1 = new LinkButton();
b1.Click += new EventHandler(Button_Click);
public void Button_Click(object sender, EventArgs e) {
//redirects to another page .. (no js defined here or in the ascx surrounding this button)
}
Why doesn't this wok when my javascript is disabled, if I used no js at all when creating the button?
How do I prevent this?
Yes this is webforms (sorry, unable to comment below).

The issue is that's how web forms manages its events with the server - as I understand it anyway (correct me if I'm wrong). Use html 5 instead. You can make the page postback to the server at the same url with a query string and then on the server grab the query string. Not the best solution but it works; it will look something similar to this:
In your page:
<form id="aForm">
<button id="abutton" type"submit" formaction="thisPage.aspx?redirect=true">click me</button>
</form>
In your page load event on the server:
if (IsPostBack) {
object something = Request.QueryString["redirect"];
if (something == null)
//not redirecting
}

Related

Click a button in CefSharp browser in Windows Forms

I'm trying to click a button on a webpage (kahoot.it), and I already know that I probably need to use Javascript for that which is fine, as long as it stays with 1 line of JavaScript because that's easy to implement in WinForms. I don't have much information on the button,
only:
<button type="submit" value="Submit" class="enter-button__EnterButton-sc-1o9b9va-0 kxpxeu" data-functional-selector="join-game-pin"><span>Enter</span></button>
Could you guys please help? There's only one button on the page, maybe that helps.
You need to write a piece of javascript code and run it when the page loaded.
Run script after page loaded
To run the code after the page loaded, you can use ExecuteScriptAsyncWhenPageLoaded method or you can handle FrameLoadEnd or LoadingStateChanged.
DOM manipulation - find element, set value, click on button
For the javascript code, you can use any of the available javascript functions. for example find the element using getElemenetsByName, getElementsByTagName or getElementById.
After you found the element, you can set its value or for example for a button you can click on it by calling its click() method.
CefSharp Example - Browse a URL, fill an input and click on a button
The following code, adds a ChromiumWebBrowser control to a Form. Then it browses google and fill the search box with a text and clicks on the search button:
//using CefSharp;
//using CefSharp.WinForms;
ChromiumWebBrowser browser;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
browser = new ChromiumWebBrowser("https://www.google.com/");
browser.Dock = DockStyle.Fill;
Controls.Add(browser);
var script = #"
document.getElementsByName('q')[0].value = 'CefSharp C# Example';
document.getElementsByName('btnK')[0].click();
";
browser.ExecuteScriptAsyncWhenPageLoaded(script);
}
Example 2
In the following example, using ExecuteScriptAsync you can fill the search box with a text and clicks on the search button programmatically:
//using CefSharp;
//using CefSharp.WinForms;
ChromiumWebBrowser browser;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
browser = new ChromiumWebBrowser("https://www.google.com/");
browser.Dock = DockStyle.Fill;
Controls.Add(browser);
}
private void button1_Click(object sender, EventArgs e)
{
var script = #"
document.getElementsByName('q')[0].value = 'CefSharp C# Example';
document.getElementsByName('btnK')[0].click();
";
browser.ExecuteScriptAsync(script);
}
Note: In your case, for kahoot.it, the script should be:
var script = #"
document.getElementById('game-input').value = '123';
document.getElementsByTagName('button')[0].click();
";
Changing Target Framework version to 4.7.2 from 4.0 fixed for me
True Target Framework Version

Button Click from JS after page reload only works does not work consistently

I have an ASP.Net web app and a part I'm working on is made up three pages:
Main Page, Search User Page and Edit User Page.
The workflow is as follows:
Login and go to the Main Page. (Works Fine!)
Go to Search User Page and search for users based on some criteria. (Works Fine!)
Click on a user on the search result table and go to the Edit User Page with the user info populated. (Works Fine!)
Press a "Save and Go Back" button and go back to the search results. The expected behavior is for the search page to reload the search results (and hence if the user attributes are changed in a way that they do not meet the search criteria they are not displayed. (This works Funky!)
This is how the logic works:
In EditUserInfo.aspx.cs I have:
public partial class EditUserInfo: basePage{
protected void Page_Load(object sender, EventArgs e) {
}
protected void btnSaveAndGoBack_Click(object sender, EventArgs e) {
//Save/Update User Data
Session["SearchAfterLoad"] = true;
ClientScript.RegisterStartupScript("string".GetType(), "goBack", "<script type=\"\"text/javascript\"\" language=\"\"javascript\"\">window.history.go(-2);</script>");
}
In SearchUsersPage.aspx.cs I have:
public partial class SearchUsersPage: basePage{
public string SearchAfterLoad{
get {
if (Session["SearchAfterLoad"] != null) { return Session["SearchAfterLoad"].ToString();}
else { return String.Empty; }
}
}
}
protected void Page_Load(object sender, EventArgs e) {
}
protected void btnSearch_Click(object sender, EventArgs e) {
/*all the logic to use the UI elements to
search and populate the users in a table*/
Session["SearchAfterLoad"] = false;
}
in SearchUsersPage.aspx I have:
<script type="text/javascript">
$(document).ready(function () {
var clickButton = document.getElementById("<%= btnSearch.ClientID %>");
if ("<%=SearchAfterLoad%>" == "True") {
clickButton.click();
}
});
</script>
My issue is:
When debugging through Visual Studio (2019, 16.4.0), the logic works perfectly. However! When I open the browser and navigate to my localhost (running on local iis) to test this, it will NOT click that search button and the search results do not get updated.
Other observations:
This works fine on my colleague's PC with the same windows and the same VS fine no matter if we are debugging or just visiting the localhost. However it does not run when deployed to our test server.
It seems the first time we navigate to the search page, the if statement in the document.ready() function translates to:
if ("" == "True")
and never gets updated/re-rendered to if("True" == "True") when we go back to that page from the edit user page.
P.S. Session["SearchAfterLoad"] is preserved and not lost when I move back and forth between the pages (but to be honest I have only verified it when in debug mode)
Things That I have tried:
In the btnSaveAndGoBack_Click() function called the URL directly by putting it into Response.Redirect() or by assigning it to window.location.href but then the search page is loaded fresh with no search criteria populated in its UI (just like visiting it the first time ever)
Play with SessionStateServer and ASP.Net Session Manager, These dont have any effect.
Looking forward:
Any good hint as to what the problem could be. Or,
Or get the iis/ or whoever in charge to rebuild that page when we go back to it so I get my if("True" == "True") .
For all other fool-proof ways to trigger that button click. Or,
Any alternate way of going back and forth between the pages that
saves me all the headache!
The problem in my code was calling go back right after assigning a session variable which caused the session variable to reset.

Need to call a Javascript method from the code-behind

I have my code-behind class and there I have an EventListener, I need to refresh the whole page when my EventListener catches an ´Event´.
How do I do this? I have a JavaScript function in my client-side window.location.reload(true).
The problem is that the javascript never gets executed.
Code-Behind:
private void WebResponse_Msg(object sender, EventArgs e){
ClientScript.RegisterClientScriptBlock(typeof(Page), Guid.NewGuid().ToString(), "refresh();", true);
}
JS:
<script type="text/javascript">
function refresh() {
window.location.reload(true);
}
</script>
Server side code can not trigger javascript (client side code) whenever you want (like when an event is triggered).
However there are several workarounds that I mention 2 of them:
1.Using SignalR
2.Logging that event when triggered in a Session, and checking the session value by ajax periodically.

pop up messages once aspx

currently I am facing a problem with pop up msgs.
The messages should prompt out first time click on a NEXT button.
when we go to the next pages and back to the previous pages, and click on the same NEXT button, the pop up msgs should not appear.
how can i fix this?
This is button code
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1" Text="Next" Width="100px" />
This is the function() for my clickedOnce
<script type="text/javascript">
window.document.onload = function()
{
var clickedOnce = false;
Button1.Button1_Click1 = function ()
{
if(!confirm('Please make sure the employee particulars and reporting line details are correct before save. \nClick OK to save and continue if all details are correct.\nClick Cancel and contact HR Admin if details appear is not up to date.'))return false;
clickedOnce = true;
}
}
</script>
Thank you. your kindness and help much appreciated.
Well, since you only want to run it once, could you give the user a cookie that lasts until the browsing session is over when they fist click the button? If they have the cookie, then you could skip over the line of code that you only want to run once.
Your code doesn't work at all. The main issue is how you try to catch click event.
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1" Text="Next" />
It means that Button1_Click1 function runs at server. No client-side event occurs. To do something on client side you have to add onclientclick="someFunction()" to your button declaration.
OK, you add this. Now go to javascript.
function someFunction(){
var clickOnce = getCookie('clickOnce');
//Look #Darkrifts comment (link) how to do it.
//Just in case I reproduce the link http://www.w3schools.com/js/js_cookies.asp
if(!clickOnce || confirm('blah blah')){
document.cookie = 'clickOnce=1';
//no need to return anything
}
//if a visitor doesn't click "ok" then the popup appear again
}
It is also possible to set Session["clickOnce"] = true; on server side and use it from Page_Load server side handler but it may not work if a visitor return to the page using browser Back button.
protected void Button1_Click1(object sender, EventArgs e){
Session["clickOnce"] = true;
//more code
}
protected void Page_Load(object sender, EventArgs e){
if(Session["clickOnce"] != true)
Button1.OnClientClick = "someFunction()";
else
Button1.OnClientClick = "";
//more code
}
This can be achieved in multiple ways. You need to select the most efficient approach for your need. First of all you need to understand the ASP.Net page life cycle, persisting information between pages and ViewState.
In a nutshell...
Whenever your page reloads all elements (including JavaScript variables, be it global or local variables) in your page get's initialised. And then a feature in ASP.Net comes into play. I.e. ViewState. If this is set to true in page level or for each control it'll persist information of the controls in the page (depends on how you set this). But, this is page specific.
And, you could persist information between pages using following approaches
Query string
Session variables
Cache
Form posts
Cookies
Data store (e.g. text, xml or any other database/ data store)
Before you use any of the above mentioned approaches you must think about your requirement. #Alex Kudryashev came up with a good example while I was writing this answer. Let me know if you need example with a different approach or any clarifications.

jQuery call error on Page_Load

I have the following code to register a javascript function on Page_Load (also tried it on Page_Init). The javascript switches two panels from hidden to shown based on a parameter on load of page:
protected void Page_Load(object sender, EventArgs e)
{
String switchAction = "<script language='javascript'>switchactionpanel(" + (int)((Global.upAction)Enum.Parse(typeof(Global.upAction), Global.ProfileAction.ToString())) + ")</script>";
Page.RegisterClientScriptBlock("switchaction", switchAction);
}
But when the page loads I am receiving an error: $ is not defined.
I looked in Firebug and the jQuery files are being loaded however, the first file that is being loaded in the .Net tab is the page itself. I know the jquery is correct as the same code works on a different page. Where should my RegisterClientScriptBlock be put in the page lifecycle to work correctly when the page loads? Or am I going about this all wrong?
You just need to ensure that the inserted script gets inserted after the JQuery reference.
Use RegisterStartupScript instead -- that inserts the script tag before </form> closing tag.
Not sure if this is relevant but I always use:
<script type="text/javascript"...
Sorry this should have been a comment rather than an answer.
I think it has to do with the register function your using. Try using RegisterStartupScript instead of RegisterClientScriptBlock.
Page.ClientScript.RegisterStartupScript(this.GetType(), "switchaction", "<script language='javascript'>switchactionpanel(" + (int)((Global.upAction)Enum.Parse(typeof(Global.upAction), Global.ProfileAction.ToString())) + ")</script>", false);

Categories

Resources