Calling from this page:
contact.aspx
protected void Page_Load(object sender, EventArgs e)
{
ctrlWebMessage=WebApplication1.About;
ctrlWebMessage.Show(this.Page, "Please enter my name");
}
about.aspx.cs -
public void Show(System.Web.UI.Page page, string strMessage) {
page.ClientScript.RegisterStartupScript(page.GetType(), "PopUp",
"<script>showDialogModal('MMF Portal', '" + strTmp + "')</script>");
}
about.aspx
function showDialogModal(message) {
var confirm = window.alert(message)
if (confirm) {
return "Yes";
`enter code here`
} else {
`enter code here`
return "No";
}
}
Well, the background does not go blank, it NEVER displays (and that is a significant different issue). When you click ok on that dialog box, then the rest of the page does display, right?
So, I would consider adopting some kind of toast message, or some kind of non blocking message box.
So, if that alert() is the first thing to display then it does display, and thus the result of the page is halted from display.
So, you need to use a dailog that is non blocking (jquery.UI) is really nice.
Remember full page post back, run your code behind and then inject a alert dialog.
Now, code behind is done, and WHOLE page goes back to client, it loads into the browser, and first thing that runs is the alert script (so, page looks blank - it just not had a chance to re-plot).
You can as a quick workaround put in a delay before the alert() is to pop up.
Say, like this:
string myscript
= "setTimeout(function() { alert('Hello to world')}, 500)";
Page.ClientScript.RegisterStartupScript(Page.GetType(), "MyPop", myscript, true);
So above will work, but I suggest you consider a jquery.UI dialog - it will work since they are async in nature.
Related
Can someone please take a look at this form
http://www.zoopla.co.uk/friend/42816744?section=for-sale&search_identifier=6323219902a84fc51cd97861178ef6ce
Using chromedriver is fine but PhantomJS won't click the submit button, well maybe it does click it but the form isn't being sent.
JavaScript executor - nothing
Using the button id - nothing
Using the button xpath - nothing
Waiting 1 minute before clicking the button - nothing
Waiting 1 minute after clicking the button - nothing
Used 5 different version of PhantomJS - nothing
Set different user agents - nothing
Set different SSL allowances - nothing
Used .click() - nothing
Used .submit() - nothing
Used .submit() on other form elements - nothing
Set different window sizes - nothing
Assert the element is displayed returns true
No errors in the log
None of these options works. When I take a screenshot I can see the fields have been populated with the data but the form just isn't being submitted, I'm not taken to the thank you page.
I can go to the page, enter NO data and submit the form and I will see the client side error message display telling me the field is required.
What could possibly be causing this?
Update adding a section of code, note that this does work in Chrome so it can't be a coding error:
public void fillInForm(){
//Enters all the details
}
// Tried all three of these findBy, I do initalise the elements in the page construtor PageFactory.initElements(this.driver, this);
//#FindBy(id="friend_submit")
//#FindBy(xpath="//input[#type='submit']")
#FindBy(xpath="//div//input[#type='submit']")
private WebElement submitEmailButton;
public void submitForm(){
Assert.assertTrue(submitEmailButton.isDisplayed());
webclientTestHelpers.scrollToElement(submitEmailButton, driver);
// Trying to click using Java script
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('friend_submit').click();");
System.out.println("WE ARE ON::" + driver.getCurrentUrl()); // Page not moved
System.out.println(submitEmailButton.isDisplayed() + "" + submitEmailButton.isEnabled()); // returns true ture so obviously the button click didn't work
submitEmailButton.click();
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
try {
FileUtils.copyFile(scrFile, new File("C:\\screenshot\\TOOKASHOT.png")); // THis screenshot displays all the form details are correctly set so clicking the button should have sent the form
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I needed to show a message on web page. I'm using ASP.Net and C#. I added below code in the back-end code to show message to the user
protected void btnRenew_Click(object sender, ImageClickEventArgs e)
{
//other code removed for clarity on where and how this alert is triggered
if (newExpiryDate.Date == memberDetails.ExpiryDate.Date)
{
Response.Write("<script>alert('Invalid renewal date');</script>");
}
}
This works fine as expected on the event call. But, the moment I click OK button on the alert message, the font-size of the text increases. It looks like somehow this alert message is disturbing my styles on the page.
Does anyone know a safe method to display alert from ASP.Net code behind page?
It is hard to tell what is causing the font shift based on what you posted, but your design can be vastly improved by 1. not making a server call just to validate a date, and 2. not using alert() which locks the whole browser until someone clicks "ok".
You could change your approach to set a few variables in javascript on page load, and then trigger a function on say change of your input or even on button click. your check function could look something like this
_memberExpiryDate = new Date('#memberDetails.ExpiryDate.Date'); // or whatever the notation is to write out server variable here
function validate() {
if (new Date($('#myDateInput').value()) >= _memberExpiryDate.getTime()))
$('#invalidDateLabel').show();
}
this way you're not making unnecessary postbacks, validation can autocorrect as users adjust dates, and there are no alerts in your face.
you can also use a library such as Toastr to show a more graceful message which disappears after a few seconds. but ideally you want to show something right next to the input field like asp.net date validator even
toastr.error('date is expired');
Also you could just use the asp.net range Validator.
See if
<script>setTimeout(function(){alert('Invalid renewal date');},1000);</script>
fixes your issue
Using ClientRegisterScriptBlock
protected void btnRenew_Click(object sender, ImageClickEventArgs e)
{
//other code removed for clarity on where and how this alert is triggered
if (newExpiryDate.Date == memberDetails.ExpiryDate.Date)
{
ClientScript.RegisterClientScriptBlock
("".GetType(), "s", "<script>alert('Invalid renewal date');</script>");
}
}
This renders the script in the HEAD section
I have Javascript function which i need to call at code behind in vb.net. The Main problem is it is not called properly because there is redirection to next page before this function executes. I do not want to call this function on Onclick event of button or something like that i want to call it after some specific condition in code behind. I have already tried following solutions please let me know if you have some other suggestions.
System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, Me.GetType(), "Script", "ShowEntryPermForm();", True)
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Window", "ShowEntryPermForm();", True)
Problem Description: added from comment
The scenario is that in javascript function i have checked various conditions related to the project and it open up a pop up window where user enter his or her comments.
It is not necessary every time the function will open the pop up window. But by default the page redirects to new page as both the functions Javascript and redirection to another window are run on click event of the button.
But now my requirement is changed now i have to call the function from code behind in particular condition. Hope you get it now
You can do this in following way.
window.onbeforeunload = function()
{
//your code goes here
return "";
}
If you return anything here then browser will display and ask user whether to leave the page. In your case you don't need to return anything but runs the code.
The only way is to Separate the code and javascript in the way they will not rely on each other
for example you make an hidden asp:button with the rest of server side code
server side :
if(...) then
page.ClientScript.RegisterStartupScript(Me.GetType(), "Window", "ShowEntryPermForm();", True)
else
page.ClientScript.RegisterStartupScript(Me.GetType(), "Window", "otherfunction();", True)
end if
sub IDServersideHiddenbutton(obj as object ,e as eventargs)handles IDServersideHiddenbutton.click
rest of the server side code including the redirect
end sub
client side :
javascript ShowEntryPermForm()
{
// javascript code
$("#IDServersideHiddenbutton").click();
}
javascript otherfunction()
{
//just the click
$("#IDServersideHiddenbutton").click();
}
I really don't know your code structure but You can manipulate it to work with this idea
I have a link in an update panel which calls a js method to do printing of the current window:
Print Coupon
where the js method is called on Page_Load event:
private void loadJs()
{
String flashMap = "script";
if (!Page.ClientScript.IsClientScriptBlockRegistered(this.Page.GetType(), flashMap))
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), flashMap, "function print(){ alert('test'); window.print(); return false; }", true);
}
}
When pressing the link, the alert window is shown multiple times (after I click "Ok", which seems strange) but window.print() is never called (a new tab for printing is not opened).
If I directly call javascript:window.link from href it works, but because the link is contained in an update panel, it no longer works second time (that's why I tried to register the script).
Can anybody see the issue here?
I believe window.print(); is actually calling your print() function recursively. Try changing the name of your js function.
I have a form submit button that has asp.net validators hooked up to it. If I make a javascript function to change the text to processing on click it does not work. The button flags the validators and also causes the whole page to post back. Heres the code I have:
C#
protected void Page_Load(object sender, EventArgs e)
{
btnPurchase.Attributes["onClick"] = "submit()";
}
Html
<script type="text/javascript">
function submit() {
document.getElementById("ctl00_ContentPlaceHolder1_btnPurchase").value = "Processing";
};
</script>
My goal is to change the buttons text to purchasing onclick if the form passes validation, and then in my code behind it will change back to the original value once the form posts back.
I ran across this solution which works 100% perfect. I'm using the script manager with update panels...
<script type="text/javascript">
// Get a reference to the PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Using that prm reference, hook _initializeRequest
// and _endRequest, to run our code at the begin and end
// of any async postbacks that occur.
prm.add_initializeRequest(InitializeRequest);
// Executed anytime an async postback occurs.
function InitializeRequest(sender, args) {
// Get a reference to the element that raised the postback,
// and disables it.
$get(args._postBackElement.id).disabled = true;
$get(args._postBackElement.id).value = "Processing...";
}
// Executed when the async postback completes.
function EndRequest(sender, args) {
// Get a reference to the element that raised the postback
// which is completing, and enable it.
$get(args._postBackElement.id).disabled = false;
$get(args._postBackElement.id).value = "Purchase";
}
</script>
I just asked a very similar question (which was answered):
ASP.NET Custom Button Control - How to Override OnClientClick But Preserve Existing Behaviour?
Essentially you need to preserve the existing behaviour of the submit button (__doPostBack). You do this with Page.GetPostBackEventReference(myButton).
However with validation it's more difficult, so you'll need to do page validation inline (Page.Validate()) or create a custom control like i did and override the OnClientClick and PostBackOptions members.
Custom control is better, as i can now just drop this control on any page i want this behaviour.
You could do the same and expose a public property:
public string loadingText {get; set;}
Which could be used to customise the loading text on each page.
You basically need to set the onclick attribute to do the following:
onclick = "if (Page_Validate()) this.text = 'Processing';{0} else return false;"
{0} should be the regular postback action, retrieved from Page.GetPostBackEventReference.
The resulting logic will be: on click, validate the page, it it succeeds, change the text and postback, if it fails, return false - which will show the validation on the page.
Have the button set to default text "Submit" in the HTML, then wrap the above logic in !Page.IsPostBack so it will reset the text on form submit.
Hope that helps.