Hossein Zahed

Web Developer, Entrepreneur, Software Educator

How to Avoid Re-Submitting Data on Page Refresh?

Here I will explain you how to prevent re-submitting data on browser page reload or refresh in your asp.net WebForm using C#. Sometimes we have some web pages through which we submit some user data to the database one after another on the same page. But the problem is, when we submit one user data and then refresh/reload our browser, what happens? The previously submitted data is re-submitted to the database. Here I am going to tell you how to prevent that.
 
Here below controls are taken in the WebForm:
1. TextBox TextBox1
2. Button SubmitBtn
 
And my work is when we type something in the TextBox1 and click on the SubmitBtn the page shows the given text of the TextBox1. And then if I refresh/reload the page it shows that the page is refreshed, not shows the text again. To do this I've used Session, ViewState and PreRender Event of the page.
Here is the C# Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            Session["Time"] = DateTime.Now.ToString();
    }
    protected void Page_PreRender(object sender, EventArgs e)
    {
        ViewState["Time"] = Session["Time"];
    }
    protected void SubmitBtn_Click(object sender, EventArgs e)
    {
        if (Session["Time"].ToString() == ViewState["Time"].ToString())
        {
            // Code for submitting data....
            Response.Write(TextBox1.Text + " Submitted!");
            TextBox1.Text = null;
            
            Session["Time"] = DateTime.Now.ToString();

        }
        else
        {
            // Code for page refresh....
            TextBox1.Text = null;
            Response.Write("Page Refreshed!");
        }
    }
}

Scroll to top of page with jQuery

Due to cross browser oddness, some browsers will respond to 'html' and some to 'body'. And maybe its just my luck, but .scrollTop(0) has never worked for me to move the page. Give this a shot:

jQuery('html,body').animate({scrollTop:0},0);

This version is tested and cross browser for all desktop browsers, and mobile devices. You may also use these:

jQuery('body').scrollTop(0);

or this:

jQuery(window).scrollTop(0);

or finally this:

jQuery('html').scrollTop(0);

Simulate a Windows Service Using ASP.NET to Run Scheduled Jobs

Back in 2005 Omar Al Zabir (Co-founder and CTO of PageFlakes) posted an article on the CodeProject web site Simulate a Windows Service using ASP.NET to run scheduled jobs that many of you have probably seen. If you liked the idea at the time but didn’t do anything with it, you may want to take another look now. In the comments, dselkirk provided an alternative that really cleans things up that Erichero then improved upon slightly and converted to C#. 

The code from the comments is below. I can confirm it works. I have not modified it in any way. All credit goes to Omar, dselkirk and Erichero.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;

/// <summary>
/// Summary description for Scheduler
/// </summary>
public class Scheduler
{

    private class CacheItem
    {
        public string Name;
        public Callback Callback;
        public Cache Cache;
        public DateTime LastRun;
    }

    public delegate void Callback();

    private static int _numberOfMinutes = 1;

    public static void Run(string name, int minutes, Callback callbackMethod)
    {
        _numberOfMinutes = minutes;

        CacheItem cache = new CacheItem();
        cache.Name = name;
        cache.Callback = callbackMethod;
        cache.Cache = HttpRuntime.Cache;
        cache.LastRun = DateTime.Now;
        AddCacheObject(cache);
    }

    private static void AddCacheObject(CacheItem cache)
    {
        if (cache.Cache[cache.Name] == null)
        {
            cache.Cache.Add(cache.Name, cache, null,
                DateTime.Now.AddMinutes(_numberOfMinutes), Cache.NoSlidingExpiration,
                CacheItemPriority.NotRemovable, CacheCallback);
        }
    }
    
    private static void CacheCallback(string key, object value, CacheItemRemovedReason reason)
    {
        CacheItem obj_cache = (CacheItem)value;

        if (obj_cache.LastRun < DateTime.Now)
        {
            if (obj_cache.Callback != null)
            {
                obj_cache.Callback.Invoke();
            }
            obj_cache.LastRun = DateTime.Now;
        }
        AddCacheObject(obj_cache);
    }
}

Example usage (code goes in the Aplication_Start event in Global.asax):

void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
        Scheduler.Run("Task1", 1, RunScheduledTasks);
    }

public void RunScheduledTasks()
    {
        WebClient client = new WebClient();
        client.DownloadData("http://localhost/ScheduledTest1/TestPage.aspx");
    }