Delay submit, perform action and then submit - c#

I am currently working on a project in Umbraco that requires a multi-stage booking process.
During this process I have multiple models that act as each stage of the booking process. These all form part of an overall parent model which is used to drive the whole process.
When the first stage is submitted, the information on the page is passed to the controller, validated and processed. Once this has been done the user is directed back to the page and the second stage of the process is displayed.
I know this probably sounds a bit mental but trust me it is the way that you have to do in Umbraco with its custom routing.
The problem I have with this is my booking process is in the middle of the page and when the page reloads it scrolls to the top.
My idea was to capture the current scroll position of the page using Javascript and pass it into my model on form submit however to do this I would need to trigger the capture and injection of this data into my form when the user clicks the submit button.
Is there therefore a way in which I can disable the default behaviour of a button:
e.preventDefault()
Perform some logic:
var top = $('html').offset().top;
Then re-initialise the default behaviour of the submit button so that it submits after performing this logic.
$(this).unbind('submit').submit();
I have tried the following but it just seems to submit the form as if nothing is happening.
$(document).ready(function(){
$('#BKG_Next').on("click",function(e){
e.preventDefault();
var top = $('html').offset().top;
alert(top);
$(this).unbind('submit').submit();
})
})
Any help would be greatly appreciated.

After some digging and further exploring I came up with the following:
var sleep = false;
$('#BKG_Next').on("click",function(e){
if(!sleep){
e.preventDefault();
var top = $(window).scrollTop();
var $element = $(this);
$('#position').value(top);
setTimeout(function(){
slept = true;
$element.click();
}, 100);
}else{
slept = false;
}
})

Related

Clear POST data after submission so user can't click Back in browser

My form when redirected to the thank you page after completion seems to retain all the data in the values field so if the user clicks back everything is there meaning they can just resubmit it and its super annoying.
if (emailSent) {
Response.BufferOutput = true;
Response.Redirect("MYDOMAIN/redirect.aspx");
};
Above is where I redirect after the form has been submitted. For my code to pull the data I am using:
Request.Form[randomFormField]
When I redirect and then click back everything is there.
$(".submitBut").click(function() {
$(this).closest('form').find("input[type=text], textarea").val("");
window.location.href('MYREDIRECTDMAIN/redirect.aspx');
});
Above is another one of my attempts
I have tried a variety of different things and nothing seems to work. I need an ASP.NET solution or C# or JQuery.
Javascript on page load: clear all form fields
Uhm....
$(document).ready(function() {
$(':input').val('');
});
References:
Input
Clearing

ASP.NET How to Ensure ViewState is Cleared to Prevent MAC Validation Error at Logon

I have inherited an ASP.NET site (4.5). The site is running on a single server (in a hosted environment) using an automatically generated ViewState encryption key.
Whenever the site is restarted, in spite of users being correctly re-directed to the login page (which is basically an asp:Login control with some text), they will get MAC verification errors until they close their browser.
I would like to know if it is possible/how to ensure that the ViewState is completely culled / cleared whenever a user logs-in to prevent this problem from happening. Do I need to do a brute-force re-direct or something similar?
I note that the login control's DestinationPageUrl is set to a static value, rather than the page in the query string, would this be an issue?
Answers that suggest disabling ViewState validation, generating static keys or implementing persistent ViewState handling will be down-voted. Thanks.
I believe this is well-covered by the SO post linked below, and probably a few others and blogs (googling "viewstate mac validation failed" reveals a number of explanations and fixes.)
Validation of viewstate MAC failed when on page for 20+ minutes
In some cases setting PostBackUrl on the login Button to equal the page name that you will be posting back to will fix the issue.
I had a case where it did not, and I was selling a COTS product and could not always rely on users updating their configuration to avoid this notorious issue. To overcome this issue, I used a little bit of javascript. The solution goes like so:
Create a "splash screen" page which can also function as a screen saver, perhaps it could show a logo and randomly move it around the page every few seconds for a nice effect (I did this). Clicking on or hitting a key on the splash screen page should navigate the user to the login form page URL.
From the Login form, render the value of Session.Timeout (integer in minutes) into javascript.
Write a javascript function that fires on window.load and uses setInterval() or the like to monitor how long the unauthenticated-user has been sitting on your login form. When the session timeout is about to expire, redirect to the splash screen page created in #1.
(Instead of the splash screen method, you could force a refresh of the login form - but if a user leaves their browser on your login form over the weekend this will prevent your ASP.NET app from automatically shutting down due to inactivity (assuming you have a site that has low enough traffic volume to actually shutdown due to inactivity)).
Example code: (put this in your login.aspx)
<script type="text/javascript">
var sessionTimeout = <%=Session.Timeout.ToString()%>;
var sessionTimeoutMs = sessionTimeout * 1000;
var refreshLoginForm = false;
var redirectToSplashPage = true;
setTimeout(function()
{
if(window.console && window.console.log) { window.console.log("ASP.NET Session expired."); }
if(refreshLoginForm)
{
// method 1: refresh login form to get a fresh viewstate
window.location.href = window.location.href;
}
else if (redirectToSplashPage)
{
// method 2: redirect to a splash screen / screen saver page
// that will link back to login form and request a fresh viewstate.
window.location.href = "login_splashscreen.html";
}
}, sessionTimeoutMs);
</script>

div.Visible not executing before other code

I am making a web app in asp.net using c# that collects a lot of information from http web services at one time. Since this data collection process takes 10-20 seconds, I want to display a small loading frame with a small rotating image.
To make this happen on one page, I have a div called loadingdiv for which I set the Visible property of to false during PageLoad. When my "find movies" button is pressed, the c# code is supposed to hide the content that was originally on the page, show the loading image while loading the web service information in the backend, then hide the loading image and bring up the data display div.
If I comment out the class that loads the data from the webservices, this works fine. But as soon as I add my web service information it completely skips over the loadingdiv.Visible = true line and just does the 10-20 second operation.
Here's the relevant lines of code.
protected void btnFindMovies_Click(object sender, EventArgs e)
{
//Hides the main content that contained search options for movies
thisarticle.Visible = false;
articlediv.Visible = false;
lblGenres.Visible = false;
ratingdiv.Visible = false;
List<int> gList = new List<int>(); //Genre List
/* Other code that goes through checkboxes to find out which genres
to search for in the movie search */
string title = "Movie Title Here";
Page.Title = title;
loadingdiv.Visible = true; //Shows loading div before completing search
MovieSearch search = new MovieSearch(gList); //Intensive web service use
(10-20 seconds)
loadingdiv.Visible = false; //removes the loading div from the screen
}
How can I get the loadingdiv to show up while my web service operations are going through?
Everything in that method happens before any response is served to the user. This means that the following happens:
The user clicks your button.
A request is sent to the server and a postback occurs.
During the postback, btnFindMovies_Click is fired. You set Visible = true, wait for the web services to return their information and then set Visible = false.
The response is served to the browser.
Because this is all done on the same request, nothing is returned to the browser until all of this is done, which effectively eliminates the loadingdiv.Visible = true; line entirely.
If you want a loading div to show while some server-side code issues requests to web services, you will have to use AJAX to make these calls asynchronously and use Javascript to hide/show the loading div accordingly.
The following looks like a useful introductory guide to AJAX:
http://www.simple-talk.com/dotnet/asp.net/ajax-basics-with-jquery-in-asp.net/

MVC 4 with jQuery Mobile page seems to be caching and controller method not being called

EDIT
Figured it out.. $.ajaxSetup({ cache: false }); wasn't working because i had data-ajax set to turned off on the form and therefore i wasn't able to set no cache ajax on it.. just for completeness if anybody knows how to get this done WHILE dada-ajax is set to false then please post so here
Something else that I just tried and it worked was to simply add data-ajax="false" to any link that you want a page refresh on. Meaning that if I have data-ajax="false" on a link it will always refresh the page before showing it!
For example the link I had a problem with was
Add a new weekly update
and the problem was that for some reason that page was caching and always showing the cached page.. So one of the easy fixes was to add data-ajax="false" to it and that forced a reload of the page everytime
Add a new weekly update
````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````
Question:
I have a options menu which brings up a form which also has a cancel and submit button.
Once the form is submitted there is certain validation that runs and if something is missing it returns to the form with some validation text.
Now if I click the cancel button at anytime i should be brought back to the options menu and if I click on the same button that brings up the form i should see a brand new clean form and this works fine if I do it before the validation.
The problem is that if I submit a non valid form which returns with the error validation messages and THEN press cancel it seems that the page becomes cached or something similar because from that point on anytime I click on the form options menu button the same form shows up each with the validation errors and data. I put a break point in the method that returns the form View() and they are never hit so for some reason it skips the entire method which creates a new form and somehow just shows the old page.
The cancel button is the following
Cancel
Does anybody know what is happening? is it being cached somehow when it returns to the same page with the validation errors??
** EDIT **
I Tried adding [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] in front of the controller by to no avail..
I also now added
$.ajaxSetup({ cache: false });
to the top of my $(document).ready(function () but that also does not seem to be doing anything, do I just put it there or do I have to call it somehow?
I checked System.Web.HttpContext.Current.Cache and the page doesn't show up there.
Have you tried setting the output cache options on the controller action like
[OutputCache(Duration=600,VaryByParam="id")]
You might also want to try making sure jquery is not caching the request as well. You can globally turn off jquery ajax caching using the information here: How to set cache: false in jQuery.get call
You can try using $.mobile.changePage() to transition to the page, it allows you to set some options, one of which is reloadPage.
reloadPage (boolean, default: false) Forces a reload of a page, even if it is already in the DOM of the page container. Used only when
the 'to' argument of changePage() is a URL.
Source: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You could work this into your link with something like:
<script>
function changeMyPage(url) {
$.mobile.changePage(url, { reloadPage : true });
}
</script>
Cancel
jquery Mobile pulls multiple pseudo-pages into the DOM at one time and normally deletes (.removes()) a pseudo-page after you've navigated away from it. It however sounds like that's not happening so you may need to use my above code (or something similar) to force a refresh of the page.
You need to clear your ModelState before hand.
This should work:
if (ModelState.IsValid)
{
//saving
if (result > 0)
{
**ModelState.Clear();**
return View(new CategoryViewModel());
}
}
How to Clear model after submit the data in database in MVC3

How to prevent multiple posts on MVC3?

A user wants to post in his blog, he fills the field and click submit.
The site is running slow, he clicks again, and again, and again.
It was finally saved, but now he check his posts and sees 4 posts.
How can I prevent this from happening? If the user click to submit once I want to do nothing for the next clicks or abort previous and start a new post, whichever makes more sense or is recommended.
In a form with
#using (Ajax.BeginForm(...))
{
}
The easiest way to achieve this is to disable submit buttons after click.
Add the following javascript (jQuery) to your view:
$(function () {
$('input[type="submit"]').click(function() {
$(this).attr('disabled', 'disabled');
});
});
Remember to enable buttons after ajax request complete if neccessary:
$('input[type="submit"]').removeAttr('disabled');
UPDATE:
It's better to disable the submit button in forms submit event handler, because an user can submit the form by pressing enter button:
$(function () {
$('form').submit(function() {
$('input[type="submit"]', this).attr('disabled', 'disabled');
});
});
There are many solutions.
One is to create a random GUID with
the form as a hidden field which is
inserted into database with the post.
Before inserting, it checks if GUID
already exists.
Alternatively you can use a real property such as DateTime (which is sent to the client side as a hidden field) or "Post title".
How about the minute the user clicks on the action link for the post area you create a real post but set its "Status" to draft?. After you InsertOnSubmit() the post immediately redirect to an action which you retrieve the post and edit it. This happens so fast the user will not notice. So if the site is slow and he clicks on "Submit" multiple times you will not be generating new records just saving to the same record. I using the process on an task list application I working on. See the code below.
Better Task List Ticket Controller
It may not be the fanciest solution but could lead you to a more creative solution that works for you.
My vote is for ActionFilters. This blog post has code to just drop into your project and decorate your actions.

Categories