How to clear texbox after submission - asp.net

Hi i wanted to know if there is any way that i can reset my form after the data has been added successfully into the database? Like after showing some message to the client the textbox should automatically clear out.
What should I write in this block:
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Label2.ForeColor = System.Drawing.Color.DeepSkyBlue;
Label2.Text = "Master added successfully";
}
else
{
Label2.Text = "Master not added";
}

2 ways :
You can do it in server side :
TextBox.Text=string.Empty; (at PageLoad or PreRender). ( I'd choose Prerender cuz your form might use the old value...)
You can do it using javascript/jQuery :
$(function (){$("form")[0].reset()});
or this.form.reset()

Related

How to Pass Variables in ASP.NET PostBack?

I'm trying to pass variables back to an ASP.NET web page by PostBack. The status variables for button presses are stored in ViewState. The problem here is that I need to press the button twice before the changed status is sent to the page.
The ViewState is read by Page_Load:
protected void Page_Load (object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["Print"] = "Small";
Response.Write ("Status: " + ViewState["Status"].ToString());
}
else
Response.Write ("Status: " + ViewState["Status"].ToString());
}
The ViewState for a button press is set by:
protected void ImageButton_LargeStatus_Click (object sender, ImageClickEventArgs e)
{
ViewState["Status"] = "Large";
}
Why do I need to press the ImageButton twice to change the ViewState?
Thanks.
Because 1st time you are updating ViewState with wrong key...
Replace below line
ViewState["Print"] = "Small";
with
ViewState["Status"] = "Small";

How to update CheckBoxes on the client side after making changes on the server side?

I have a DropDownList and a CheckBox on my web form. After the DropDownList is clicked and this event is posted back to the server. DropDownList_SelectedIndexChanged event is called on the server side. Inside that event handler, I have CheckBox.Checked = true, But I couldn't make the page on the client side to reflect this change (CheckBox.Checked = true). How do I achieve this? Or am I in the wrong direction to use the DropDownList's event handler to update the CheckBox because the page firstly reloads and then DropDownList_SelectedIndexChanged is called?
Page load method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.DropDownList1.Items.Clear();
AddItemsToDropDownList();
}
}
DropDownList selected index changed event handler:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selected = this.DropDownList1.SelectedItem.Text;
CheckBox checkBox = GetCheckBoxToBeSetByText(selected);
checkBox.Checked = true;
}
OK. Found the issue. Actually there is nothing wrong with the code in my original post. But to make a smallest sample when I posted, I removed some "extra" code. The below is the "complete" code (OK, fine, I still removed some code). As you can see, I put the CheckBox into a static Dictionary. Each time the SelectedIndexChanged event handler is called, it's modifying the CheckBox in that static Dictionary, which means it's modifying the CheckBox object created from the last session? (still not clear here) Looks like each time when a postback message is received, a new set of CheckBox objects are created. Bear with me if this is known to everybody here already because I only have two days of experience on this web development thing up to today.
private static Dictionary<Environment, CheckBox> EnvironmentsCheckBoxes;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
EnvironmentsCheckBoxes = new Dictionary<Environment,CheckBox>();
EnvironmentsCheckBoxes.Add(Environment.Dev1, this.Dev1_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.Dev2, this.Dev2_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.QA, this.QA_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.QA2, this.QA2_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.Demo, this.Demo_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.Prod, this.Prod_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.UAT, this.UAT_CheckBox);
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selected = this.DropDownList1.SelectedItem.Text;
if (selected == "Dev1")
{
EnvironmentsCheckBoxes[Environment.Dev1].Checked = true;
}
else if (selected == "Dev2")
{
...
}
...
}

Sending values from one page to another using sessions

I am sending values from send page to receive page using sessions, its working fine but the problem is I remember the URL and i directly run receive page its shows previous information but it's invalid is it....?
If end user directly visit receive page i need to restrict or give some message something like that
How can i overcome this problem..............
This is my code
send.aspx.cs
protected void gv_rowcommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow grow = (GridViewRow)(((LinkButton)e.CommandSource)).NamingContainer;
Session["c"] = grow.Cells[0].Text;
Session["s"] = grow.Cells[1].Text;
Session["e"] = grow.Cells[2].Text;
Session["t"] = grow.Cells[3].Text;
Session["a"] = grow.Cells[4].Text;
Response.Redirect("confirmation.aspx");
}
}
confirmation.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
lblgetcourse.Text = Convert.ToString(Session["c"]);
lblgetstartdate.Text = Convert.ToString(Session["s"]);
lblgetenddate.Text = Convert.ToString(Session["e"]);
lblgettimings.Text = Convert.ToString(Session["t"]);
lblgetamount.Text = Convert.ToString(Session["a"]);
}
Once you have displayed the values on the confirmation page you could remove them from the Session.
Session.Remove("c");
...
This will ensure that the confirmation page will always display fresh values coming from the send.aspx page. You could also check for the presence of those values in the session before displaying them.
On Confirmation Page, Fetch the Values from Session Variables an display them , then Clear Session variables just like: Session.Clear();
You can check the referrer header :
Request.UrlReferrer
and see where the request comes from.
so your page_load will look like :
protected void Page_Load(object sender, EventArgs e)
{
if (!Request.UrlReferrer=='...') Response.Redirect("~/login.aspx");
...
protected void Page_Load(object sender, EventArgs e)
{
if(Request.UrlReferrer.AbsolutePath == "~/send.aspx")
{
lblgetcourse.Text = Convert.ToString(Session["c"]);
lblgetstartdate.Text = Convert.ToString(Session["s"]);
lblgetenddate.Text = Convert.ToString(Session["e"]);
lblgettimings.Text = Convert.ToString(Session["t"]);
lblgetamount.Text = Convert.ToString(Session["a"]);
}
else
{
//do something
}
}

After Response.Redirect() don't display label

First I have login form (Najava.aspx) who check the status :
if (Session["Status"].ToString() == "0")
{
Response.Redirect("Najava.aspx");
Label3.Text = "You waiting activation!";
}
With this I check if the user is not activated. I redirect again to the login form and I like in label to display text, but label don't display text after redirect?
One possibility is to set the text inside the Page_Load event of Najava.aspx. And if you need to display it only conditionally then you could pass a query string parameter when redirecting and then display the label only if this parameter is present:
if (Session["Status"].ToString() == "0")
{
Response.Redirect("Najava.aspx?waitingactivation=true");
}
and then inside the Page_Load event of Najava.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request["waitingactivation"]))
{
Label3.Text = "You waiting activation!";
}
}
Also you might consider using forms authentication.

Prevent Page Refresh in C#

Duplicate of Asp.Net Button Event on refresh fires again??? GUID?
hello, ive a website and when a user click a button and the page postback, if the user refresh the Page or hit F5 the button method is called again.
any one know some method to prevent page refresh with out redirect the page to the same page again ?
something like if (page.isRefresh) or something... or if exist any javascript solution is better.
this seen to works.... but when i refresh it does not postback but show the before value in the textbox
http://www.dotnetspider.com/resources/4040-IsPageRefresh-ASP-NET.aspx
private Boolean IsPageRefresh = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["postids"] = System.Guid.NewGuid().ToString();
Session["postid"] = ViewState["postids"].ToString();
TextBox1.Text = "Hi";
}
else
{
if (ViewState["postids"].ToString() != Session["postid"].ToString())
{
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Session["postid"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (!IsPageRefresh) // check that page is not refreshed by browser.
{
TextBox2.Text = TextBox1.Text + "#";
}
}
Thanks for comments and sorry for my mistake,
I found this code in:
http://www.codeproject.com/KB/aspnet/Detecting_Refresh.aspx
And this time tested ;)
private bool _refreshState;
private bool _isRefresh;
protected override void LoadViewState(object savedState)
{
object[] AllStates = (object[])savedState;
base.LoadViewState(AllStates[0]);
_refreshState = bool.Parse(AllStates[1].ToString());
_isRefresh = _refreshState == bool.Parse(Session["__ISREFRESH"].ToString());
}
protected override object SaveViewState()
{
Session["__ISREFRESH"] = _refreshState;
object[] AllStates = new object[2];
AllStates[0] = base.SaveViewState();
AllStates[1] = !(_refreshState);
return AllStates;
}
protected void btn_Click(object sender, EventArgs e)
{
if (!_isRefresh)
Response.Write(DateTime.Now.Millisecond.ToString());
}
You can test for the Page.IsPostBack property to see if the page is responding to an initial request or if it's handling a PostBack such as your button click event. Here's a bit more information: w3schools on IsPostBack
Unfortunately that's not going to solve your problem since IsPostBack will be true when the user clicks the button as well as when they refresh the page after the button action has taken place.
If you're doing a task like performing CRUD on some data, you can Response.Redirect the user back to the same page when you're done processing and get around this problem. It has the side benefit of reloading your content (assuming you added a record to the DB it would now show in the page...) and prevents the refresh problem behavior. The only caveat is they still resubmit the form by going back in their history.
Postbacks were a bad implementation choice for the Asp.net and generally are what ruin the Webforms platform for me.
This doesn't solve the problem.
First of all, storing a token in the view state is not a good idea, since it can be disabled. Use control state instead. Although, a HttpModule is a better solution.
All in all, this will not work anyway. If you open another tab/window the session will be invalid for the previous tab/window. Therefore braking it. You must somehow store a unique value each time a page is first loaded. Use that to determine where the request came from and then check the "refresh ticket". As you may see, the object for one user might get pretty big depending on the amount of requests made, where and how long you store this information.
I haven't seen any solution to this I'm afraid, as it is pretty complex.
bool IsPageRefresh ;
if (Page.IsPostBack)
{
if (ViewState["postid"].ToString() != Session["postid"].ToString())
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postid"] = Session["postid"];
I tried many ways and I ended up looking for the form data sent when the postback / refresh is triggered... I found that there is a Key for any VIEWSTATE created and you can just compare those Keys like...
I put that on my custom basepage to reuse it like an Property
public bool IsPageRefresh = false;
protected void Page_Init(object sender, EventArgs e)
{
if (IsPostBack)
{
var rForm = Request.Form;
var vw = rForm["__EVENTVALIDATION"].ToString();
var svw = Session["__EVENTVALIDATION"] ?? "";
if (vw.Equals(svw)) IsPageRefresh = true;
Session["__EVENTVALIDATION"] = vw;
}
}

Resources