form post back related - asp.net

I have one form with submit button in asp.net and C#. Form is for submitting comment to website webmaster through email. C# code is as below.
but facing one problem. i.e. on refreshing the page it again sends the comment in email due to postback. How can I avoid this? here is the code...
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string body = "";
//body = body + "<html><head></head><body>";
body = body + "Dear Balvignan Team,\r\n";
if (txtComment.Text != null)
{
body = body + "Comment: " + txtComment.Text;
}
if (SendEmail(txtEmail.Text.Trim(), "Comment", body, false) == true)
{
lblContactAcknowledge.Text = "Thank You For <br />Submitting comment.";
lblContactAcknowledge.Visible = true;
PnlTalkToUs.Visible = false;
}
else
{
lblContactAcknowledge.Visible = false;
PnlTalkToUs.Visible = true;
}
}
SendEmail is function to send email.

You can use the Page.IsPostBack Property to check, if its a Postback or page refresh.

You might use the following option:
if (SendEmail(txtEmail.Text.Trim(), "Comment", body, false) == true)
{
Response.Redirect("contact.aspx?success=true");
}
else
{
Response.Redirect("contact.aspx");
}
On Page Load
if (!Page.IsPostback)
{
if (Request.QueryString["success"] == "true" )
{
lblContactAcknowledge.Text = "Thank You For <br />Submitting comment.";
lblContactAcknowledge.Visible = true;
PnlTalkToUs.Visible = false;
}
else
{
lblContactAcknowledge.Visible = false;
PnlTalkToUs.Visible = true;
}
}
When the user refreshes the page (ctrl + r, f5, etc) will to a GET request, not a POST request.
EDIT another solution
Another solution is to use ViewState:
public bool EmailSent
{
get
{
return ViewState["EmailSent"] != null ? (bool)ViewState["EmailSent"] : false;
}
set
{
ViewState["EmailSent"] = value;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
....
if (!EmailSent)
{
if (SendEmail(txtEmail.Text.Trim(), "Comment", body, false) == true)
{
...
EmailSent = true;
}
else
{
...
}
}
}

In your page_load event
if(page.isPostback==NO)
{
//send an email
}
else
{
//Don't send
}

Related

ASP.net Page pageload called in postback with IsPost back = false

Hi everyone i have a strange problem which I hope u can help me with,
i have a normal Asp.net page in which i handle some state data in the page load like this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["TempD"] = null;
Session["Totals"] = null;
//Handling Sessions here...
}
}
the problem is at a button post back the page_load gets called twice once with IsPostBack
= true which is ok , the second time however IsPostBack = false!!! which cause my code to enter the if condition and reset the state information which is not ok, i use some Ajax Toolkit controls in the page no update panels just some calenders and AutoCompletes.
here is the code for the button causing the post back
protected void TSBtnAddItem_Click(object sender, EventArgs e)
{
if (Session["TempD"] != null)
{
DataLayer.Invoicing.CInvoiceDetail InvoDetails = (DataLayer.Invoicing.CInvoiceDetail)Session["TempD"];
DataLayer.Invoicing.CVarInvoiceDetail var = new DataLayer.Invoicing.CVarInvoiceDetail();
if (LblCurrencyValue.Visible)
{
var.CurencyID = int.Parse(LblCurrencyValue.ToolTip);
}
else
{
var.CurencyID = int.Parse(CboCurrencyValue.SelectedValue);
}
var.ID = 0;
var.InvoiceHeaderID = Convert.ToInt64(InvoiceHeaderID.Value);
var.IsChanges = true;
var.IsFreightItem = false;
var.IsOption = true;
var.ItemAmount = decimal.Parse(txtItemVal.Text);
var.ItemName = CboItemName.SelectedItem.Text;
var.ItemID = int.Parse(CboItemName.SelectedValue);
var.Remarks = "";
if (IsPartLoad.Checked == true)
{
ShipLink.Publics.ApplicationMethods.Item32 itm = LstCalcType.Find(delegate(ShipLink.Publics.ApplicationMethods.Item32 p1) { return Convert.ToInt32(p1.Name.Trim()) == var.ItemID; });
if (itm == null)
{
ADDToCalcList(Convert.ToString(var.ItemID));
if (NumUpDownPortRatio.Enabled == false)
var.ItemAmount = ChangeAmount(var.ItemID, var.ItemAmount);
}
}
InvoDetails.lstCVarInvoiceDetail.Add(var);
Session["TempD"] = InvoDetails;
UGrdInvoiceDetailGrid.DataSource = InvoDetails.lstCVarInvoiceDetail;
UGrdInvoiceDetailGrid.DataBind();
CalcSalesTax();
CalcDiscount();
AddCaseUGrdInvoiceTotalGrid();
}
}
Have a look at this: What is the difference between Page.IsPostBack and Page.IsCallBack?
Integrate if (!IsCallBack) and you should be fine.
I found a solution for this. If you have an global.asax in the project, you need add a new route with "" in a url alias. An example:
private void Generteroutes(RouteCollection routes) {
routes.MapPageRoute("home", "", "~/Default.aspx");
}
load this in Application_Start and problem solved.

SelectedIndexChanged not firing

My problem is that SelectedIndexChanged of ddlObra control is not firing, but when I erase the Page.ClientScript.RegisterOnSubmitStatement of Page_Load, everything works fine. I can't understand this behavior.
Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CarregarDropDownLists();
}
Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "OnSubmitScript", "return handleSubmit()");
}
protected void ddlObra_SelectedIndexChanged(object sender, EventArgs e)
{
List<Entidades.Empreendimento.Unidade> unidades = Entidades.Empreendimento.Unidade.ListaUnidades(txtLogin.Text);
ddlBloco.Items.Clear();
ddlUnidade.Items.Clear();
ddlBloco.Items.Insert(0, new ListItem("----- Bloco -----", ""));
ddlUnidade.Items.Insert(0, new ListItem("----- Unidade -----", ""));
//if (unidades.Count == 1) return;
foreach (Entidades.Empreendimento.Unidade Un in unidades)
{
if (Un.ObraVinculo.idObraCrm.ToString() == ddlObra.SelectedValue)
{
if (!ddlBloco.Items.Contains(new ListItem(Un.BlocoCRM.Nome, Un.BlocoCRM.CodigoCRM)))
{
ddlBloco.Items.Add(new ListItem(Un.BlocoCRM.Nome, Un.BlocoCRM.CodigoCRM));
}
Bandeira = Un.Bandeira;
Estado = Un.Estado;
}
}
ddlBloco.SelectedIndex = 0;
ddlUnidade.SelectedIndex = 0;
LoadAreas();
}
This code is in the .aspx file
<script type="text/javascript">
function handleSubmit() {
if (typeof (ValidatorOnSubmit) == 'function' && ValidatorOnSubmit() == false) {
return false;
} else {
$("#btnEnviar").click(function () { return false }).fadeTo(200, 0.5);
return true;
}
}
</script>
Thank you guys for your help!
The client script executed by the submission of the form must return true in
order to allow the form to submit. This enables the client-side script to
prevent the submission of the form conditionally.

Ajax AsyncFileUpload fires server code but does not update client side

I have an asyncfileupload control inside an update panel.
In UploadedComplete, i save file to server.
protected void ImageFileUpload_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
System.Threading.Thread.Sleep(5000);
if (ImageFileUpload.HasFile)
{
Extension= System.IO.Path.GetExtension(ImageFileUpload.FileName);
TempImageUpload(ImageFileUpload.FileName.ToString(), Extension.Value);
FileImage.ImageUrl = "~/Temp/" + Session["ID"].ToString() + Extension.Value;
RemoveImageButton.Visible = true;
}
}
The file succesfully upload and fires the correct server side code.
But don't update viewstate and controls.
private string Extension
{
get {
if(ViewState["Extension"]==null)
return string.Empty;
else
return (string)ViewState["Extension"]; }
set { ViewState["Extension"] = value; }
}
I save file On UploadedComplete event.
protected void ImageFileUpload_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if (ImageFileUpload.HasFile)
{
ImageFileUpload.SaveAs(Request.PhysicalApplicationPath + "Temp\\" + Session["ID"].ToString() + extension);
}
}
and fot change control in client side, i use OnClientUploadComplete.
function uploadComplete(sender, args) {
var filename = args.get_fileName();
document.getElementById('<%= Extension.ClientID %>').value = "." + filename.split('.').pop();
var btn = document.getElementById('<%= RemoveImageButton.ClientID %>')
btn.style.visibility = 'visible';
}

Using Global.asax to set/check session variable and redirect (for user testing)

I would like to add very simple, temporary security to my site.
I made a page at Home/UnderConstruction where people testing the site can enter a hard-coded password which will then set the "underconstruction" session variable to "false".
This is what I have so far, but it results in too many redirects:
protected void Session_Start(Object sender, EventArgs e)
{
HttpContext.Current.Session["underconstruction"] = "true";
}
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
var underconstruction = HttpContext.Current.Session["underconstruction"];
if (underconstruction != null)
{
string oc = underconstruction.ToString();
if (oc != "false") Response.Redirect("~/Home/UnderConstruction");
}
}
}
Is this close to what I would need to do?
Here is the code we got to work:
Controller Code for UnderConstruction View
public ViewResult UnderConstruction()
{
return View();
}
[HttpPost]
public ActionResult UnderConstruction(string ocp)
{
if (ocp == "mypassword")
{
Session["underconstruction"] = "false";
return RedirectToAction("Index", "Home");
}
else
{
Session["beingredirected"] = "false";
return View();
}
}
Global.Asax
protected void Session_Start(Object sender, EventArgs e)
{
HttpContext.Current.Session["underconstruction"] = "true";
HttpContext.Current.Session["beingredirected"] = "false";
}
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
bool uc = false;
var underconstruction = HttpContext.Current.Session["underconstruction"];
if (underconstruction != null)
{
uc = Boolean.Parse(underconstruction.ToString());
}
bool redirected = false;
var beingredirected = HttpContext.Current.Session["beingredirected"];
if (beingredirected != null)
{
redirected = Boolean.Parse(beingredirected.ToString());
}
if (uc && !redirected)
{
if (Request.HttpMethod == "GET")
{
HttpContext.Current.Session["beingredirected"] = "true";
Response.Redirect("~/Home/UnderConstruction");
}
else if (Request.HttpMethod == "POST")
{
}
}
HttpContext.Current.Session["beingredirected"] = "false";
}
}
Is ~/Home/UnderConstruction in a different website? If not, wont it always redirect because oc will always be true? ie - do you also need to add a check for the page you're requesting so you can bypass the redirect if already going to the UnderConstruction page?
UPDATE
Not sure if checking the page name is a great idea, but something like this might work:
protected void Session_Start(Object sender, EventArgs e)
{
HttpContext.Current.Session["underconstruction"] = "true";
HttpContext.Current.Session["beingredirected"] = "false";
}
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
bool uc = false;
var underconstruction = HttpContext.Current.Session["underconstruction"];
if (underconstruction != null)
{
uc = Boolean.Parse(underconstruction);
}
bool redirected = false;
var beingredirected = HttpContext.Current.Session["beingredirected"];
if (beingredirected != null)
{
redirected = Boolean.Parse(beingredirected);
}
if (uc && !redirected)
{
HttpContext.Current.Session["beingredirected"] = "true";
Response.Redirect("~/Home/UnderConstruction");
}
HttpContext.Current.Session["beingredirected"] = "false";
}
}
Note that I would clean that up, that example was to just give the general idea.
UPDATE
If you want to use roles as mentioned in the comments, then this article from ScottGu's Blog may help. Its a little more complicated, but has the added benefit of not introducing temporary code as the above solution will

User Control events

I have a problem while writting event for ImageUpload User control.
I want to add a event that fire on imagebutton click in this case that green ok button. I write some code for event but it get raised on pageload() and on postback, so it causes a problem --> Image path which is provided for image upload is get clear after image upload but on a page refresh a same image is upload again and again on every page refresh.
User Control Code
public partial class Gallery_Controls_ImgUpload : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{ }
public string TxtDesc
{
get {return txtimgdesc.Text;}
set { txtimgdesc.Text = value; }
}
public string TxtImgName
{
get { return txtimgname.Text; }
set { txtimgname.Text = value; }
}
public FileUpload ImgUpld
{
get { return ImgUpload; }
//set { ImgUpload = value; }
}
public string ImgAttr
{
get { return ImgUpload.Attributes["onchange"]; }
set { ImgUpload.Attributes["onchange"] = value; }
}
public event EventHandler ImgBtnUpClick;
protected void imgbtnok_Click(object sender,EventArgs e)
{
ImgBtnUpClick(ImgUpload, e);
}
Code for Adding control in page and upload a file
public partial class Gallery_iupload : System.Web.UI.Page
{
ASP.gallery_controls_imgupload_ascx upctrl;
protected void Page_Load(object sender, EventArgs e)
{
upctrl = (ASP.gallery_controls_imgupload_ascx)LoadControl ("Controls/ImgUpload.ascx");
upctrl.ImgBtnUpClick += new EventHandler(Upload);
upctrl.ImgAttr = "checkFileExtension(this); return false;";
PlaceHolderupctrl.Controls.Add(upctrl);
}
protected void Upload(object sender, EventArgs e)
{
TextBox txtbximgname = (TextBox)upctrl.FindControl("txtimgname");
TextBox txtbxdesc = (TextBox)upctrl.FindControl("txtimgdesc");
FileUpload Imgload = (FileUpload)sender;
if (Imgload.HasFile)
try{
Imgload.SaveAs("C:\\Uploads\\" + txtbximgname.Text + ".jpg");
Label1.Text = "File name: " + Imgload.PostedFile.FileName + "<br>" +
Imgload.PostedFile.ContentLength + " kb<br>" +"Content type: " +
Imgload.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label1.Text = "You have not specified a file.";
}
}
}
you have to put a IsPostBack check in your page_load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{ upctrl = (ASP.gallery_controls_imgupload_ascx)LoadControl ("Controls/ImgUpload.ascx");
upctrl.ImgBtnUpClick += new EventHandler(Upload);
upctrl.ImgAttr = "checkFileExtension(this); return false;";
PlaceHolderupctrl.Controls.Add(upctrl);
}
}

Resources