which method is better to prevent re-insertion of data into database after refreshing the page ?
should I check the database everytime I insert a row or using the viewState and session is more efficient?
protected void Page_Load(object sender, EventArgs e)
{
/* check refresh */
if (IsPostBack == false)
{
Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
//rest of the codes
}
protected void Page_PreRender(object sender, EventArgs e)
{
// set both session and viewstate value equal
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}
protected void btnSaveTazkera_Click(object sender, EventArgs e)
{
if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
{
//give a new value to session
Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
//rest of the code
}
tnx.
Using the session is more effective, but also may not be 100% safe (what if I don’t refresh the page, but re-open the browser and enter the same information again? Session is new and data will still be inserted twice).
If you want to prevent double insertion of records into the database, the easiest way is to create a respective primary key or do the insertion via a stored procedure that checks whether inserting is OK or not.
You can still use the session as an additional check before inserting, but the final check should be left to the database/the code that inserts into the database.
But this is only my opinion and how I’d do it. I don’t think there’s anything like a standard thing to do 🙂