Avoid Simultaneous clicks of buttons in MVC - c#

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;
});

Related

Force user to click button at least once before posting

I want the user to click a button to add a row on my page before they post the form info.
Basically there is a button on the page which adds a string line to a div, and i want to make sure they've clicked this button at least once. If they have they can successfully post, if not i want to display an error message saying the div must have at least 1 item inside of it
Im not sure how to approach solving this issue. Should i use jQuery? Is there a way to do this with DataAnnotations
jQuery seems like a good fit for this:
/* Lets declare a global boolean variable to hold the status of having at least one item in the div */
var rowAdded = false;
// listen for the add-row click. When clicked, toggle rowAdded.
$('button').click(function() {
rowAdded = true;
});
// listen for the form submission and check rowAdded before sending the form.
$('#submit').click(function() {
if(rowAdded){
// submit the form
} else {
// user has not added a string row to the div, prompt them to add a row.
// prompt method 1, use alert()
alert('Please add a row before submitting this form.');
// prompt method 2, print string to the dom
var promptString = 'Please add a row before submitting this form.';
$('#prompt-div').append('<p>' + promptString + '</p>');
}
});
Will users know what to do?
Can you not just add a checkbox that indicates: [] check this to add a row, then a button to submit?
you can simply hide the submit button (or disable it) and show only the button to add that row and when it's clicked show the submit button

Browser back button do not clear the previous input Textbox values

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">

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

how to avoid postback when i click the button in MVC

I have two button in my cshtml page. When i click the first button data fetch from the database and bind it my controls. The records are many so the second button goes down, then i click the second button same thing happened fetch from the database and bind the grid, so the page is loaded then the page goes up. I want to stay same place when i click the second button. How to prevent it.
make your button like this :
<input type="button" id"button2" onclick="CallAjax();return false;"/>
//then in javascript
function CallAjax()
{
//your ajax call here to retrieve or update data
}
This is MVC 101...
Make your button a standard HTML5 button, which calls a JavaScript function on click...
<input type="button" id="goButton" value="Go »" onclick="goFunction();">
(I don't think you have to "return false" with a button, only with a submit)
Then, use Razor helpers in your view to do the Ajax call to the controller...
function goFunction() {
var url = '#Url.Action("MyActionMethodName", "MyControllerName")';
var settings = { 'some data': 'some values' };
$.ajax(url, settings);
}
See the JQuery Ajax page for more information about how to work the "settings" object.
BTW - sounds like you are "paging a grid" but you just forgot to say so... use a tool for that, such as Kendo. Paging is solved, don't solve it again.

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