Page upload data again on page refresh in ASP.NET - asp.net

For some reason when the user click on the submit button and he re-fresh the page the same data get's uploaded again to my SQL Server 2005 database. I do not what this to happen........... Why is this happening? I am making use of a SQL Data Source!!
My code
Try
'See if user typed the correct code.
If Me.txtSecurity.Text = Session("Captcha") Then
If Session("NotifyMe") = "Yes" Then
SendEmailNS()
End If
RaterRate.Insert()
RaterRate.Update()
DisableItems()
lblResultNS.Text = "Thank you for leaving a comment"
LoadCompanyList()
LoadRateRecords()
txtCommentNS.Text = ""
txtSecurity.Text = ""
lblResultNS.Focus()
Else
Session("Captcha") = GenerateCAPTCHACode()
txtSecurity.Text = ""
txtSecurity.Focus()
Validator10.Validate()
End If
Catch ex As Exception
lblResultNS.Visible = True
lblResultNS.Text = ex.Message.ToString
lblResultNS.Focus()
End Try

When user visiting your page, generating new captcha. after when post or else, its checking captcha but not generating new. Move 'captcha set' code to outer scope.
If Me.txtSecurity.Text = Session("Captcha") Then
...
Else
...
End If
Session("Captcha") = GenerateCAPTCHACode()

This is happening because of the nature of WebForms relying on the PostBack model. Every time you click on a button the single form you have inside the page is posted to the server along with the viewstate. When you press F5 you normally get a warning that the form will be reposted and if you click Yes the same action is executed on the server. One way to avoid this is to perform a redirect after you save to the database:
Response.Redirect("~/success.aspx");

Related

How to validate TextBox?

I have a textbox for a zipcode in which i hav made a validation that the user cannot enter number less then or more then 6, but even if user enters 3 nos it is working.SO i want an error msg to display if user enters something wrong
Private Shared Function ValidateZip(ByVal pintZip As String, ByRef pobjErrMsg As Common.ErrorMessage) As Boolean
If pintZip.Length <> 6 Then
ElseIf IsNumeric(pintZip) Then
End If
Return True
End Function
You have no code in either the If or ElseIf blocks and you are always returning True
Private Shared Function ValidateZip(ByVal pintZip As String, ByRef pobjErrMsg As Common.ErrorMessage) As Boolean
If pintZip.Length <> 6 Then
MsgBox("Zip code should have 6 characters")
pintZip.Focus
Return False
ElseIf IsNumeric(pintZip) Then
MsgBox("Congratulations, you have entered right Zip code")
Return True
End If
End Function
Try like this
UPDATE #1
Seems like you are using ASP.net not VB.net, here is the answer:
You can't show dialog box ON SERVER from ASP.NET application, it makes no sense since your user is using browser and it can't see message boxes on server. You have to understand how web sites work, server side code (ASP.NET in your case) produces html, javascript etc on server and then browser loads that content and displays it to the user, so in order to present modal message box to the user you have to use Javascript, for example alert function.
Here is the example for asp.net :
example
SOURCE

Classic ASP VBScript - refresh given page

I think that this is something very easy, but I cannot get this to work.
I have a form with a button "Delete". It calls www.mypage.com/adm/ads.asp?del=12.
So list.asp sees that there is a querystring with del=12 and deletes correspoding item.
After delete I want to refresh this page (something like Response.Redirect www.mypage.com/adm/ads.asp), so that querystring del=12 disappears.
I cannot get it working.
If (Request.QueryString("del").Count > 0) Then
id = Request.QueryString("del")
sql = "delete from Ads where ID = " & id & ""
on error resume next
conn.Execute sql
If err<>0 then
Response.Write("Delete error!")
Else
Response.Redirect http://www.mypage.com/adm/ads.asp
//Call opener.location.reload()
End if
The page is reloaded, but del doesn't disappear from query string.
The parameter to Response.Redirect should be a string - what you have is a syntax error:
Response.Redirect http://www.mypage.com/adm/ads.asp
Should be:
Response.Redirect "http://www.mypage.com/adm/ads.asp"
To make it generic and not mess with raw URLs you can have such code instead:
Response.Redirect(Request.ServerVariables("SCRIPT_NAME"))
The SCRIPT_NAME server variable will return the relative path of the currently executing script, no matter what the page is called and where it's located.

Call a ASPX from two different ASPX Pages

I have three ASPX Pages. The ASPX Page which get called from the two other Page is a Page where i can Upload files.
I call that Upload-Page from the other two Pages with JavaScript:
function UploadFax_Click() {
var grid = ISGetObject("WebGrid1");
var curSelObj = grid.GetSelectedObject(); // get selected object
var row = curSelObj.GetRowObject(); // get the WebGridRow object
if (row.Type == "Record") {
var s_id = row.KeyValue
}
window.location = '../Admin/UploadFax.aspx?suppid=' + s_id;
}
Then on the Upload-Page i get the QueryString:
If Not IsPostBack And Len(Request.QueryString("suppid")) > 0 Then
If Not Request.QueryString("suppid") Is Nothing Then
Session("suppid") = Request.QueryString("suppid")
End If
End If
What i need is that if i call the Upload-Page from one of the two Pages the functions of the Upload-Page should be restricted.
For Example: If i call the Upload-Page then Checkbox.Disabled = true and from the other page Checkbox should be enabled.
My idea was to send a second parameter from that page, then get the parameter with Request.QueryString and then use if/else to enable oder disable that checkbox.
Question is, is there another, better possibility to do that what i want? If yes how can i do that?
Using QueryString may cause a security violation , Why not you use Session parameter,
when you Call it from the First Page then set
Session("IsCalled")="1"
in the second page load check
IF Not Session("IsCalled") Is Nothing AndAlso Session("IsCalled")="1" Then
CheckBox1.Enabled=False
End If
and Vise Versa in the first page load.
You can check the Request.UrlReferrer and dance from it:
Dim restrictedAccess As Boolean = Not IsNothing(Request.UrlReferrer) AndAlso
Request.UrlReferrer.AbsolutePath.IndexOf("/Original.aspx", StringComparison.InvariantCultureIgnoreCase) >= 0
Checkbox.Disabled = Not restrictedAccess

vbscript server side validation

Basically I have a page named dvds.asp with a form that goes to action="process.asp". The process.asp script validates the Name, Surname and Email fields. I would like that if the email does not exist, a redirect will occur to the original page (dvd.asp) and also display a custom error.
The validation of the email field and redirect I know how to do. The only problem is how I am going to get the custom error value in the dvds.asp.
Any help please? :)
FYI:
I am using this code in process.asp to validate:
if txtEmail = "" then
Server.Transfer(Request.ServerVariables("HTTP_REFERER"))
else
Now the error I want to show on the dvds.asp page is: "Please fill in your email" .. How I can do that please?
Hard to say without seeing any source, (For instance, how are you validating the email? What is this "Custom error value"?
Assuming you have a function that validates the email and returns false if it fails and the matching error value is "1" then you could simply include this in your redirect:
Dim EmailAddress
EmailAddress = Request.Form("EmailAddress")
If ValidateEmail(EmailAddress) = False Then
Response.Redirect("dvd.asp?ErrorID=1")
End If
and on the Origional Source page, you could just display errors back to the user as follows:
'#### Output errors
If Trim(Request.QueryString("ErrorID")) <> "" Then
Select Case Request.QueryString("ErrorID")
Case "1" ' #### Email Error
Response.Write("<p><span style=""color: red"">Error: Invalid email address</span></p>")
Case "2" ' #### Bad Name
Response.Write("<p><span style=""color: red"">Error: Invalid Name</span></p>")
Case Else
Response.Write("<p><span style=""color: red"">Error: Unknown / Generic Error</span></p>")
End Select
End If
One small suggestion by the way, its often preferable for pages such as this to post to the same page and include any email functionality you need from a class / SSI. That way you cold auto-populate the form again if an error occurred rather than expecting your end user to re-type the whole form if they get an error.

Get selectedIndex from a dropdown list on submit

This is my first web page ever and I can't seem to find the correct way to get the selected index from a dropdown list. I don't need the selected index until the user presses the submit button. I've been testing everything I've found on the subject, but nothing is working.
I don't want the drop-down box to reset when the selection is made, which is what happens if I use postback=true or any selected index changed events. And, I still get an index of 0.
When I test, the selected index is always zero.
This runs on page load:
ddlBudgetLineItem.DataSource = budget.BudgetLineItems;
ddlBudgetLineItem.DataTextField = "Name";
ddlBudgetLineItem.DataValueField = "BudgetLineItemID";
ddlBudgetLineItem.DataBind();
This is the drop-down list:
<asp:DropDownList ID="ddlBudgetLineItem" runat="server">
</asp:DropDownList>
Here is the code that needs the index:
protected void submitPayment()
{
string amountValue = txtAmount.Text.ToString();
float amount = float.Parse(amountValue);
Payment payment = new Payment()
{
Amount = amount,
Payee = txtPayee.Text,
BudgetLineItem = budget.BudgetLineItems[ddlBudgetLineItem.SelectedIndex],
Memo = txtMemo.Text,
PaymentDate = DateTime.Parse(txtPaymentDate.Text),
ExtraUserInfo = info
};
provider.AddPayment(payment);
}
Any assistance is appreciated.
it seems to be a life cycle issue, this is happening because everytime (on a postback or not) the page is loaded, your dropdown is rebuilt (caused by ddlBudgetLineItem.DataBind()), concluding that on a postback your ddl will get index=0 forever.
how can you solve this:
1: Override the page databind method and put your code before call base.databind(); (inside the method)
2: on your load event you just have to call databind (if not is postback), it prevent to rebuild your object states everytime your page is loaded.(cause of your lost information).
3: take a look on a page lifecycle it will help you to prevent future issues like that.

Resources