Unable to use <% ... %> in a client side button click event - javascript

I am trying to redirect to a different page based upon a value in the querystring. This is an asp.net web form page. When the cancel button is clicked the following js should execute. The button is an devexpress button.
function OnCancelClick(s, e) {
if (confirm('If you leave this page, you have to reselect the benefits. Are you sure to leave this page?')) {
var callingPage = document.getElementById("<%= CallingPage.ClientID %>").value;
alert("Calling Page: " + callingPage);
if (callingPage == "AddEmployee.aspx") {
window.location.href = ResolveUrl('~/Member/Maintenance/AddEmployee.aspx?from=VerifyPage');
} else if (callingPage == "AddDependentMember.aspx") {
}
}
CallingPage is the ID of an asp hidden field. I am setting its value during the page load. Even before this page is loaded I am getting The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)
error. Not sure whether it is due to devexpress button control or something else.

Assign the CallingPage.ClientID to a server side page variable with public accessibility:
public partial class <class / page name> : System.Web.UI.Page
{
public string callingPage = "";
protected void Page_Load(object sender, EventArgs e)
{
this.callingPage = CallingPage.ClientID;
...
}
}
then in your javascript:
var callingPage = document.getElementById("<%= this.callingPage %>").value;

Actually this is an unique issue related to devexpress controls. It looks like that we can't use <% %> within the js clientside click event of a devexpress button click event. Instead I used devexpress's hidden control, then it worked fine.
Thanks

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.

LinkButton click doesn't trigger with no 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
}

ASP.NET redirect from event handler hot by button clicked by JavaScript

I have a problem with a page not redirecting during a postback.
I have an aspx-page with this content being part of it:
<td class="tdinput" align="right">
<asp:Button ID="ButtonFrigiv" runat="server" Text="Frigiv sag" CssClass="button"
OnClientClick="verifyReleaseOtherEmployeesCase()" />
<asp:Button runat="server" ID="ButtonFrigivHidden" OnClick="ButtonFrigiv_Click"
Style="display: none;" UseSubmitBehavior="true" />
</td>
The page also contains various UpdatePanels, however the above code is not included in one.
As it is seen there's a button being displayed, which calls the following JavaScript:
function verifyReleaseOtherEmployeesCase() {
var logonUser = document.getElementById('<%= HiddenLogonUser.ClientID %>');
var lockedBy = document.getElementById('<%= HiddenLockedBy.ClientID %>');
var button = document.getElementById('<%= ButtonFrigivHidden.ClientID %>');
if (logonUser.value == lockedBy.value) {
button.click();
}
else if (confirm("Danish confirm message")) {
button.click();
}
else {
return;
}
}
So basically this JavaScript locates the 2nd button above (which is not being displayed to the user) and clicks it.
When the button is clicked the following event handler is reached on the server:
protected void ButtonFrigiv_Click(object sender, EventArgs e)
{
NyeSagerDAC.FrigivSag(SagID, LogonUser);
Response.Redirect(LastList);
}
Where LastList is a string containing the page which was the entry point for the current page (there are multiple entry points).
The server method is reached and the first line in the method is executed perfectly, however the page is not redirected.
I have done some testing regarding whether it might have been considered an AJAX-callback (which doesn't allow redirects) using the following code in the event handler:
HttpRequest request = HttpContext.Current.Request;
string header = request.Headers["X-MicrosoftAjax"];
The content of the string header is empty and the Page_Load is called after the event handler is done. So I don't think this is the problem.
I have also tried to register a startup script to have the page redirect itself instead. This has been tried in various ways:
Page.ClientScript.RegisterStartupScript(GetType(),"redirect",
"window.location.href='" + LastList + "'");
And
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect",
"window.location.href='" + LastList + "';", true);
However none of this seems to work.
The only thing I have got to work was when I removed the confirm() part of the JavaScript and had it just click the button. This resulted in the page being correctly reloaded. However, I need to ask the user actually wants to unlock another employee's task.
So I think my question is: How can I get the page to redirect? Alternatively, how can I modify the JavaScript to still ask the user to confirm and not stopping the redirect from working?
The solution is coded in .NET 4.0
Thanks in advance.
Your js function is named verifyReleaseOtherEmployeesCase but in the OnClientClick it says verifyReleaseOtherWorkersCase, assuming that is a typo you also need to prevent the first button from performing a postback.
Notice the return of false in the js function and the return in the OnClientClick
function verifyReleaseOtherEmployeesCase() {
var logonUser = document.getElementById('<%= HiddenLogonUser.ClientID %>');
var lockedBy = document.getElementById('<%= HiddenLockedBy.ClientID %>');
var button = document.getElementById('<%= ButtonFrigivHidden.ClientID %>');
if (logonUser.value == lockedBy.value) {
button.click();
}
else if (confirm("Danish confirm message")) {
button.click();
}
return false;
}
<asp:Button ID="ButtonFrigiv" runat="server" Text="Frigiv sag" CssClass="button"
OnClientClick="return verifyReleaseOtherEmployeesCase()" />

Trouble with page reload. ASP.NET

So what i have is a web application that uses c# code and javascript code. My javascript code generates some information dependant on the users input. Once this is finished it is saved using a ASP button. Attached to the asp button is a on client click and a on click event. the Javascript code validates the code and makes sure that the string that has been created is valid. If not a error message is sent to a hidden label. The C# code then checks that label and if it is empty (if there was no problem with validation) it executes the C# code. If it has a value inside then the error message from the hidden label is passed to a visible label using the c# code and shown to the user.
However if the error message is shown the page in automatically reloaded (as it is a button click event this always happens). and the users inputs are cleared from the screen.
Is there any way i can stop the page from reloading when the error message is shown?
CODE
Javascript:
if (goalnum > 0 && blocknum > 0 && playernum == 1 && goalnum == blocknum) {
mapsave = JSON.stringify(map);
document.getElementById('<%=mapsave.ClientID %>').value = mapsave;
}
else {
document.getElementById('<%=lblError.ClientID %>').value = "Your map must have one and only one player, one or more blocks, one or more goals and the number of blocks must match up with the number of goals";
}
C#
protected void btnSave_Click(object sender, EventArgs e)
{
if (mapsave.Value.ToString() == "")
{
lblResult.Text = lblError.Value;
}
else
{
AddNodeToXMLFile("filepath.xml", "TileMaps");
}
}
Do you return false on the button click? If not, even if validation has failed a new Post will fire.
Can you post the code perhaps?

Categories

Resources