Browser back button do not clear the previous input Textbox values - c#

I have 3 textboxes, 2 dropdownlists, 2 RadGrid, 2 Poeple's picker control on a page, when user click the page's asp:button (save button), records saved to database and page redirects to another page. But when user click back button of the browser, those data input in textboxes on previous page are still there, and If again user click on asp:button without changing the textbox values, duplicate records are saved into database. Previous input value only persist for Textboxes not for any other control on click of back button. Please let me know how to solve this issue. My all textbox controls are inside asp:FormView. Thanks in advance.

Try stop browser caching.
The back button doesn't always reload the page.
// Stop Caching in IE
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
// Stop Caching in Firefox
Response.Cache.SetNoStore();
Check following for detail:
How does the Back button in a web browser work?
Disabling browser caching for all browsers from ASP.NET

Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).
If you have to do something in case of user hitting back/forward keys -- listen for BFCache pageshow and pagehide events.
A pseudo jQuery example:
$(window).bind("pageshow", function() {
// update hidden input field
});
See more details for Gecko and WebKit implementations.

See It helps you:
In JavaScript, onbeforeunloadevent is fired when the page is about to unload and there can be multiple reasons for this unload. For instance, back or forward or refresh button is clicked or a link on the page is clicked, etc.
Normally, onbeforeunloadevent is used in order to handle browser back button functionality as follows:
<body onbeforeunload=”HandleBackFunctionality()”>
function HandleBackFunctionality()
{
if(window.event) //Internet Explorer
{
alert("Browser back button is clicked on Internet Explorer...");
}
else //Other browsers e.g. Chrome
{
alert("Browser back button is clicked on other browser...");
}
}
But there is a problem that identical event occurs once a user clicks on refresh button of a browser. So, to grasp whether or not refresh button or back button is clicked, we will use the subsequent code.
if(window.event.clientX < 40 && window.event.clientY < 0)
{
alert("Browser back button is clicked...");
}
else
{
alert("Browser refresh button is clicked...");
}
The above code snippet works well in browsers aside from FireFox. In case of FireFox, we need to apply the following check:
if(event.currentTarget.performance.navigation.type == 1)
{
alert("Browser refresh button is clicked...");
}
if(event.currentTarget.performance.navigation.type == 2)
{
alert("Browser back button is clicked...");
}
So, the consolidated code snippet will look as:
function HandleBackFunctionality()
{
if(window.event)
{
if(window.event.clientX < 40 && window.event.clientY < 0)
{
alert("Browser back button is clicked...");
}
else
{
alert("Browser refresh button is clicked...");
}
}
else
{
if(event.currentTarget.performance.navigation.type == 1)
{
alert("Browser refresh button is clicked...");
}
if(event.currentTarget.performance.navigation.type == 2)
{
alert("Browser back button is clicked...");
}
}
}

Simple. Add this html attribute to any field you don't want autofilled by the browser.
autocomplete="off"
for example:
<input type="email" name="email" autocomplete="off">

Related

Avoid Simultaneous clicks of buttons in MVC

I have a MVC web application with two buttons - Save and Submit.
When a user first Submits and simultaneously clicks the Save button as soon as he clicks the submit button there is a error in the data send.
I am pretty new to programming and hence have no idea how can i avoid the simultaneous clicks.
Any suggestions on how i can handle this?
Thanks
You can do the following:
Have Submit button as “Submit” button (rendered in html as input type=“submit”)
Have Save button as normal button.
To have Save button rendered as normal button (rendered as input type=“button” you can have UseSubmitBehavior: False.
You can then use OnClientClick on one of the buttons and prevent the other button from being clicked.
Here you can get creative also. You can disable the clicked button and show “Saving ...” like below:
// its a button or document.getElementById
if (button.getAttribute('type') == 'button') {
button.disabled = true;
button.className = "inactive class";
button.value = "Saving, please wait. Have some peanuts while we save...";
Try disabling the Save button in the code of the Submit button HTML onclick=" ... "
Simple solution with jQuery:
$("[type='submit']").on("click", function (e) {
// !!!IMPORTANT!!!
e.preventDefault();
var $self = $(this), $form = $self.closest("form");
// Valid - before submit
if ($form.valid()) {
// Update text in button, ex: Sending..., Loading...
$self.attr("disabled", "disabled").html("<i class='fa fa-spinner fa-pulse fa-lg fa-fw' aria-hidden='true'></i>Loading...");
// Block all inputs.
$form.find(":input:not([type=hidden])").attr("readonly", "readonly");
// Submit form.
$form[0].submit();
return true;
}
// !!!IMPORTANT!!!
return false;
});

How to hide a button when going back to previous page

I have a save button that saves the input data and a submit button that redirects to the next page. When this page first loads up, the submit button is hidden and when save is clicked, the submit button is visible and redirects to the next page when clicked. If users wants to edit the inputs, they can go back to the previous page where the inputs remain in the controls. My problem is that I want the submit button to be hidden when going to the previous page so that it forces users to save first. How do I do this?
if you use serverside conttoller
if(IsPostback)
{
btn.Visible =false;
}
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function () {
if ($("#TextBox1").val()) //if input has value
$("#Button1").hide(); //hide button
})
</script>
Server side code is not possible because on browser back no request is made, the page is retrieved from cache so it should be done with client code
Page_Load()
{
if(IsPostback)
{
btnSubmit.visible=false
}
}
If this is a web forms based application, try setting
btnSubmit.Visible = false in the Page_Load method

ASP.Net C# - Redirect to a page

I've got a 'menu' within a Master page which includes a number of image buttons with click events.
Within each click event, I want to redirect the user to a specific (Child) page. However, if the user is already on the correct (Child) page, I don't want to refresh the page and lose the entered data.
In the example below, I want to redirect the user to browse.aspx however, if the user is already on browse.aspx, I don't want to refresh it.
Is there a better way to do this than the following?
protected void ibtnBrowse_Click(object sender, ImageClickEventArgs e)
{
if (!Request.Url.Segments[1].ToString().Equals("browse.aspx"))
{
Response.Redirect("~/browse.aspx");
}
}
How about disabling the Image button on the page?
e.g.
When you are on browse.aspx, in code behind browse.aspx.cs you can disable the button.
ImageButton iBtn = (ImageButton)Page.Master.FindControl("ibtnBrowse");
iBtn.Enabled = false;
By having server side click events the page will always "refresh" when clicking on these buttons. However, if you are simply looking to avoid doing an unnecessary redirect in your code you can use:
HttpContext.Current.Request.Url.AbsoluteUri
or
HttpContext.Current.Request.Url.AbsolutePath
If you decide to use javascript to switch between pages you can use location:
location.replace("http://www.w3schools.com");
location.assign("http://www.w3schools.com");

Prevent or rollback the postback on page_load

First of all, I can't use Async plugins like Jquery, Ajax, UpdatePanel, etc.
I have an ASP.NET 4 WEBFORM, In the master page I verify if the Session is lost, in that case a show a modal to get the username/password and log-in the user again.
But I've two problems, the first one is that for example if I press a button and I lost the session, the webpage show me the modal but the code behind of the clickevent still execute it and i want to prevent it (I dont want to verify the state of the session in every event handler of the APP).
The second one is that after Im success on log-in the user, i want to finish or continue the event that the user tries before he lost the session.
I other words my problem is that I need to prevent the postback in the middle of it, and then do it again. :/
Something like this:
Page_Load(...)
{
If(Session["User"] == null)
{
PostBack.Cancel(); //Like de e.PreventDefault() of Javascript.
return;
}
.
.
}
AND
LoginOnSessionLost()
{
...
//After Login Success
Postback.Continue();
}
Any suggestions? Thanks

Testing if a button has been clicked or not

I have an asp.net page which loads and writes values from a record to the controls on the page.
There is a link to another page and a save button.
If the user clicks save, fine, the changes are saved and they can navigate to wherever.
If they dont click save and click the link, any changes are lost.
Is there a way to check if the save has been clicked while the user has that page loaded?
I'm thinking along the lines of an OnClick Javascript function for the link such as -below, I'm not sure though how to test for the save button being clicked - can anyone point me in the right direction?
function handleHyperLinkClick(hyperlink)
{
confirm("You have not clicked save, any changes will be lost - click cancel then save your changes or ok to continue");
}
Add a bool variable, that is default false, set to true if the button has been clicked. Then check the value if user leaves the page.
You can do using hidden field. when user click on save button then set hidden field value.
You have to keep a temporary variable in javascript like state;
`
var state = 0;
//your function calls here
function yourFunction()
{
//// your coding
state =1;
//// your coding
}
`
In this case, you have to submit the value or navigate to other page when state=1, otherwise you shouldnt. This flag to be checked whilst clicking link (if its navigating via function) or onBeforeUnload event for page.
Please correct me know if you are looking for something other.
You can attach some value to a variable when the button is clicked. Then when the user tries to navigate, check whether that variable has that value. If so, it has been clicked, else not:
button = document.getElementById("button");
button.onclick = function() { clicked = true; }
document.getElementById("link").onclick = function() { if (!clicked) { alert("Sure?"); }
Assuming you are using ASP.NET server buttons like this:
<asp:Button runat="server" id="someButtonId" Click="someClickHandler" Text="Continue" />
If I were you, I would use jQuery to dynamically bind the click event of the button like this:
$(document).ready(function() {
$("input[type=button][id$=someButtonId]").on("click", function(e) {
if(!confirm("You have not clicked save, any changes will be lost - click cancel then save your changes or ok to continue"))
{
e.preventDefault()
}
});
});
Hope this helps.

Categories