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
Related
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.
This is something I already know the answer to but I want to come up with a better way. I have a dropdown within a gridview. Within the method that populates the dropdown data I'm adding an an "onchange" attribute to the dropdown. The onchange calls a javascript function that is then used to fire a popup based on what the user selects on the dropdown.
My issues is I want the popup to display only once within that current page for that user. The easiest answer is to use JavaScript sessionStorage to store some dummy value that is checked before the javascript popup code is run and then set afterwards.
The problem I'm having is that I then have to manage the storage by either clearing the storage when the user goes to another page by attaching storage.clear to all the buttons dealing with moving to another page.
Is there a way that I can clear the storage after the person moves to another page other than the page they are on. BTW the dropdowns and javascript are all located within an ASP.NET custom control. That custom control is loaded within several pages, therefore I want the logic to be isolated within the custom control so that I don't have to make changes to every page that uses the control and for modularity.
You can in the page on load, just set a global js var to the page like this:
protected void Page_Load(object sender, EventArgs e)
{
string script;
if (IsPostBack)
{
script = "var isPostBack = true;";
}
else
{
script = "var isPostBack = false;";
}
Page.ClientScript.RegisterStartupScript(GetType(), "IsPostBack", script, true);
}
So, now in your js code, you can use isPostBack as a simple true/false var.
I've a legacy ASP.NET application, which I'm trying to modernize. I've a page
MyPage.aspx, and its codebehind MyPage.aspx.cs
I've replaced a custom user control (which does a fileupload) with a custom react component. The react component is working as expected. The old ascx usercontrol had an event handler which is defined in 'MyPage.aspx.cs'as follows.
protected void asyncFile_FileUploaded(object sender, FileUploadedEventArgs e)
//logic to set the uploaded file's name etc for saving.
}
Nowthat the custom control is replaced with an empty DIV, where the react component is being mounted, I'm left with no option to call my C# logic in the 'MyPage.aspx.cs' codebehind file.
I've created a 'CreateProperty.aspx.js' file which is responsible of initializing my react component inside the .aspx page, and below is the contents of this file.
$(document).ready(function () {
if ($('#Myupload').length) {
ReactDOM.render(
<Upload id="pictureupload2"
onChange={onChange}
setBusyState={onBusy}
onUploadSucceeded={onUploadSucceeded}
/>,
document.getElementById("Myupload")
);
}
});
function onChange(e) {
console.log(e);
}
function onBusy(e) {
console.log(e);
}
function onUploadSucceeded(e) {
console.log(e);
}
Once the react component has done the uploading, it calls the function onUploadSucceeded() with my required parameters. But how will I pass that value back to my MyPage.aspx.cs file ?
Please help.
Drop in a standard asp.net button on the form.
Move the code you have/had for the previous event into that button code stub
eg:
protected void asyncFile_FileUploaded(object sender, FileUploadedEventArgs e)
//logic to set the uploaded file's name etc for saving.
}
So, move the above code to the button (style="display:none) to hide it.
AND OF COURSE don't copy the event stub code!!!.
Now, in your js function, do whatever and simply "click" on that button.
The bonus here is you get the badly needed post back when the client side js/ajax runs.
So, you have this:
function onUploadSucceeded(e) {
console.log(e);
document.getElementById('<%= btnOkUpLoad.ClientID %>').click();
So, the above is nice. I mean you could do a js __DoPostBack(); in js, but then you have to pass some parameters, and then client side in the on-load page event, detect the parameters (a pain to wrire up).
So, anytime I want to run code behind from js? Just drop in a asp button, write the code stub for that button, and then client side, use the above ".click()" to run that code. As noted, in MOST cases you want a post back anyway - which is what a asp.net button does for you.
Edit: now I said we want a post back in most cases? Well, I mean when we are all said and done - and thus this button click makes sense. We certainly don't want needless post backs - but when you do, and when you want to run+call a code stub, the this button trick is nice. Just use style="display:none" to hide it from view - but js code can still use the .click() to run (click) the button for you))
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 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