Ajax + Browser history - asp.net

I am following the Managing Browser History asp.net example article but I have a problem with updating the LabelHistoryData label after clicking the browser back button. I placed a breakpoint at
LabelHistoryData.Text = Server.HtmlEncode(e.State["s"]);
but somehow after clicking btnGetInboxList or btnGetSentboxList follow by the browser back button, the LabelHistoryData.Text value is always null. Below is a portion of my code. Someone please kindly advice.
Thanks.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="True" OnNavigate="OnNavigateHistory" EnableHistory="true" EnableSecureHistoryState="false" />
<asp:UpdatePanel ID="uiupInboxMainGrid" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label runat="server" ID="LabelHistoryData" />
<asp:Button ID="btnGetMessageContent" runat="server" Text="MsgContent" OnClick="GetMessageContent_Click" />
<asp:Button ID="btnGetInboxList" runat="server" Text="Inbox" OnClick="GetInboxList_Click"/>
<asp:Button ID="btnGetSentboxList" runat="server" Text="OutBox" OnClick="GetSentBoxList_Click" />
</ContentTemplate>
</asp:UpdatePanel>
public void OnNavigateHistory(object sender, HistoryEventArgs e)
{
LabelHistoryData.Text = Server.HtmlEncode(e.State["s"]);
}
protected void GetInboxList_Click(object sender, EventArgs e)
{
LabelHistoryData.Text = ((Button)sender).Text;
ScriptManager.GetCurrent(this).AddHistoryPoint("s", LabelHistoryData.Text, "Entry: " + LabelHistoryData.Text);
}
protected void GetSentBoxList_Click(object sender, EventArgs e)
{
LabelHistoryData.Text = ((Button)sender).Text;
ScriptManager.GetCurrent(this).AddHistoryPoint("s", LabelHistoryData.Text, "Entry: " + LabelHistoryData.Text);
}
protected void GetMessageContent_Click(object sender, EventArgs e)
{
LabelHistoryData.Text = ((Button)sender).Text;
ScriptManager.GetCurrent(this).AddHistoryPoint("s", LabelHistoryData.Text, "Entry: " + LabelHistoryData.Text);
}

Turns out that the UpPanel UpdateMode has to be set to Always.

Related

Timer in ASP.NET webform to update a label text

I use this code for create timer that want to update a label each second:
timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(OnRefresh_Tick);
timer.Interval = 1000;
The function OnRefresh_Tick call each second but the label text doesn't change.
Edit:
I use the below code for the timer, but when the timer starts, I can't write in the second textbox (txtPassword) and it refreshes and the cursor goes to the first textbox (txtUserName)
.aspx file:
<form id="form1" runat="server">
<br /><br />
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtUserName" runat="server" Height="30px" Width="100px"></asp:TextBox><br /><br />
<asp:TextBox ID="txtPassword" runat="server" Height="30px" Width="100px"></asp:TextBox><br /><br />
<asp:Label runat="server" id="lnkSendVerificationCode"></asp:Label><br /><br />
<asp:Button ID="Button1" runat="server" Text="Start Timer" CssClass="btn" OnClick="Button1_Click"/>
<asp:Timer ID="Timer1" runat="server" Enabled="False" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
</form>
.cs file:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
}
}
protected void Button1_Click(object sender,EventArgs e)
{
Session["VerificationCodeCounter"] = "20";
Timer1.Enabled = true;
}//Button1_Click
protected void Timer1_Tick(object sender, EventArgs e)
{
int sendVerificationCounter = -1;
try { sendVerificationCounter = int.Parse(Session["VerificationCodeCounter"].ToString()); } catch { }//catch
if (sendVerificationCounter == 1)
{
sendVerificationCounter = -1;
Session["VerificationCodeCounter"] = sendVerificationCounter.ToString();
Timer1.Enabled = false;
}//if
else if (sendVerificationCounter > 0)
{
sendVerificationCounter--;
lnkSendVerificationCode.Text = sendVerificationCounter.ToString();
Session["VerificationCodeCounter"] = sendVerificationCounter.ToString();
}//else if
}//Button1_Click
Try say this:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div style="padding:25px">
<h4>enter seconds to count down</h4>
<asp:TextBox ID="txtCount" runat="server"
Height="42px"
Width="80px"
Font-Size="XX-Large"
Text="0"
style="text-align: center">
</asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Start Timer" CssClass="btn" OnClick="Button1_Click"/>
<asp:Timer ID="Timer1" runat="server" Enabled="False" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
<br />
</div>
And code behind would be this:
protected void Button1_Click(object sender, EventArgs e)
{
Timer1.Interval = 1000; // tick our timer each second
Timer1.Enabled = true;
}
protected void Timer1_Tick(object sender, EventArgs e)
{
int MyCount = Convert.ToInt32(txtCount.Text);
if (MyCount > 0 )
{
MyCount = MyCount - 1;
txtCount.Text = MyCount.ToString();
}
else
{
// we are done, stop the timer
Timer1.Enabled = false;
}
}
So, we now see this if we enter 10 (for 10 seconds).
If we hit start timer, then it counts down to 0, and then stops the timer.
Edit: With a up-date panel
So, if we don't want a whole page re-fresh, then we can use this:
<h4>enter seconds to count down</h4>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtCount" runat="server"
Height="42px"
Width="80px"
Font-Size="XX-Large"
Text="0"
style="text-align: center">
</asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Start Timer" CssClass="btn" OnClick="Button1_Click"/>
<asp:Timer ID="Timer1" runat="server" Enabled="False" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
Remember, while the whole page will now not re-fresh, do keep in mind that the page life cycle DOES trigger. So, if you have some code in on-page load to setup controls? Then you need this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// code here to load up grids, and controls
// code here ONLY runs on first time page load
}
}
So, keep in mind that for any up-date panel (button clicks, timer etc.), then the page load event DOES fire each time.
However, that !IsPostback check? The last 100+ web pages I created that loads or sets up ANYTHING on a page will have the above code stub, and check for !IsPostback.
You can't quite even make a working webforms page unless you follow the above rule. What this means is your page can now handle post-backs, and not re-load controls and run the first time setup of such controls.
So, keep in mind, a update panel DOES post-back, and does trigger the page load event. Better said, a update panel, and click of a button (or timer) inside will post-back, but it what we call a partial page post-back.
Edit3: With a label
So, say we want a label - not a text box. Then do this:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div style="padding:25px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="txtCount" runat="server"
Height="42px"
Width="80px"
Font-Size="XX-Large"
Text="999"
style="text-align: center">
</asp:Label>
<br />
<asp:Button ID="Button1" runat="server" Text="Start Timer" CssClass="btn" OnClick="Button1_Click"/>
<asp:Timer ID="Timer1" runat="server" Enabled="False" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
<br />
</div>
</form>
</body>
And now our code becomes this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// code here to load up grids, and controls
// code here ONLY runs on first time page load
txtCount.Text = "10";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Timer1.Interval = 1000; // tick our timer each second
Timer1.Enabled = true;
}
protected void Timer1_Tick(object sender, EventArgs e)
{
int MyCount = Convert.ToInt32(txtCount.Text);
if (MyCount > 0 )
{
MyCount = MyCount - 1;
txtCount.Text = MyCount.ToString();
}
else
{
// we are done, stop the timer
Timer1.Enabled = false;
}
}
And now we see this:

transfer listbox items from one asp.net page to another using session

Transfer listbox items from one asp.net page to another using session. I want to transfer the items of a list box from one asp.net page to another. The code somehow is throwing error. The items in the listbox are not being retrieved either. I want to do the same with a check box list. Hopefully the listbox issue will help[ me solve that too. Please advice.
First Page
<asp:ListBox ID="SelectedItems" runat="server" SelectionMode="Multiple"/>
<asp:Button ID="sbmtButton" runat="server" Text="Submit" Width="152px" OnClick="sbmtButton_Click" />
.cs for the First Page
protected void sbmtButton_Click(object sender, EventArgs e)
{Session["wrd"] = SelectedItems;Server.Transfer("~/aftrSubmit.aspx";);}
Second Page
.cs for the Second Page
protected void Page_Load(object sender, EventArgs e)
{if (!this.IsPostBack){Prescription_list = (ListBox)Session["wrd"];}}
First Page ASPX Code:
<asp:ListBox ID="SelectedItems" runat="server" SelectionMode="Multiple">
<asp:ListItem Text="A"></asp:ListItem>
<asp:ListItem Text="B"></asp:ListItem>
<asp:ListItem Text="C"></asp:ListItem>
</asp:ListBox>
<asp:Button ID="sbmtButton" runat="server" Text="Submit" Width="152px" OnClick="sbmtButton_Click" />
First Page C# Code-Behind:
protected void sbmtButton_Click(object sender, EventArgs e)
{
ListItem[] x = new ListItem[SelectedItems.Items.Count];
SelectedItems.Items.CopyTo(x, 0);
Session["wrd"] = x;
Server.Transfer("~/aftrSubmit.aspx");
}
Second Page ASPX Code:
<asp:ListBox ID="Prescription_list" runat="server" SelectionMode="Multiple"/>
Second Page C# Code-Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ListItem[] x = (ListItem[])Session["wrd"];
Prescription_list.Clear();
Prescription_list.Items.AddRange(x);
}
}

Should this be a bug or not - ASP.NET Request parameter

I posted a number of bugs on Microsoft site and while they were real bugs, MSFT will close it as design [And I figured most people favour MSFT anyways]. Here is one that I am sure they will clasify as by design but to me this is a serious bug.
This is all I have in ASPX page (NET 3.5).
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" /><br />
<asp:Label ID="lblOutput" runat="server" Text="Label"></asp:Label>
Codebehind
protected void Page_Load(object sender, EventArgs e)
{ /* this works */
if (IsPostBack)
{
string txt = string.Empty;
txt = Request.Params["TextBox1"];
lblOutput.Text = "You entered : " + txt;
}
}
protected void Button1_Click(object sender, EventArgs e)
{ /* this does not */
string txt = string.Empty;
txt = Request.Params["TextBox1"];
lblOutput.Text = "You entered : " + txt;
}
Now if you include another simple HTML textbox (Not ASP) like this
<input type="text" id="mytextbox" name="mytextbox" /> // still it below the existing one
txt = Request.Params["mytextbox"]; // change to this line instead of TextBox1
Then it works in both places.
protected void Button1_Click(object sender, EventArgs e)
{ /* Now this works which is weird but it does */
If(IsPostback)
{
string txt = string.Empty;
txt = Request.Params["TextBox1"];
lblOutput.Text = "You entered : " + txt;
}
}
I therefore should close the question.
If you are forced to use the Request object instead normal asp:* controls, use it like this:
txt = Request["TextBox1"];
It will check all the HttpRequest collections.
The QueryString, Form, Cookies, or ServerVariables collection member
specified in the key parameter. If the specified key is not found,
then null is returned.
That is really fundamental stuff you're doing in that example, so I highly doubt it's a bug. From the example, it looks like you're going against the grain:
Markup
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" />
<asp:TextBox ID="TextBox2" runat="server" />
<asp:TextBox ID="TextBox3" runat="server" />
<asp:TextBox ID="TextBox4" runat="server" />
...
</asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" /><br />
<asp:Label ID="lblOutput" runat="server" Text="Label"></asp:Label>
Code-behind
protected void Button1_Click(object sender, EventArgs e)
{
foreach (TextBox txtCtrl in PlaceHolder1.Controls.OfType<TextBox>())
{
//append the textbox value to the label
lblOutput.Text += String.Format("{0}<br/>", txtCtrl.Text);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
List<TextBox> txtList = PlaceHolder1.Controls.OfType<TextBox>().ToList();
for (int ctrlIndex = 0; ctrlIndex < txtList.Count; ctrlIndex++)
{
TextBox txtCtrl = txtList.ElementAt(ctrlIndex);
if (txtCtrl != null)
{
lblOutput.Text += String.Format("{0}<br/>", txtCtrl.Text);
}
}
}

gridview edit requires to click twice

Why is that I need to click the edit link twice, in a gridview control, before my row enters into edit mode?
<asp:ObjectDataSource ID="ods" runat="server" TypeName="Employee"
SelectMethod="GetAll" ></asp:ObjectDataSource>
<asp:GridView ID="GridView1" runat="server" CssClass="styled"
OnRowCommand="gv_RowCommand" DataSourceID="ods"
OnSorting="gv_Sorting" >
<Columns>
...........
</Columns>
<ItemTemplate>
<ItemTemplate>
<div class='actions'>
<asp:Button ID="btnEdit" runat="server" Text=" Edit " ToolTip="Edit Row" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"Id") %>' CausesValidation="False" />
<span style="padding-left:10px"></span>
</div>
</ItemTemplate>
</asp:GridView>
protected override void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.ods.SelectParameters[0].DefaultValue = "";
}
}
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == CRUID.Edit.ToString())
{
this.gv.ShowFooter = false;
}
}
You need to avoid rebinding your gridview on each postback.
If not ispostback then
GridView1.DataSource = dt
GridView1.DataBind()
end if
Otherwise you just overwrite Gridview changes.
Great explanation at this link...
http://www.pcreview.co.uk/forums/gridview-two-clicks-needed-enter-place-editing-t3328887.html
Try handling the RowEditing event to set the EditItem Index:
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = e.NewEditIndex
}
There are some mistakes in your code as i examined. Correct your code as shown below:
<asp:ObjectDataSource ID="ods" runat="server" TypeName="Employee"
SelectMethod="GetAll" ></asp:ObjectDataSource>
<asp:GridView ID="GridView1" runat="server" CssClass="styled"
OnRowCommand="gv_RowCommand" DataSourceID="ods"
OnSorting="gv_Sorting" >
<Columns>
...........
<asp:TemplateField>
<ItemTemplate>
<div class='actions'>
<asp:Button ID="btnEdit" runat="server" Text=" Edit " ToolTip="Edit Row" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"Id") %>' CausesValidation="False" />
<span style="padding-left:10px"></span>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected override void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.ods.SelectParameters[0].DefaultValue = "";
}
}
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
this.gv.ShowFooter = false;
}
}
If on using this code the problem does not solve then there may be some problem in your cssclass which you used with your GridView as I have Checked your code on my machine using ObjectDataSource and it works well using edited code.
Also I want to know that what is CRUID in CRUID.Edit.ToString()
and why you used the following line in Page_Load event
this.ods.SelectParameters[0].DefaultValue = "";
as there are no parameter associated with your SelectMethod="GetAll" method used in ObjectDataSource.
May this answer help you.
I guess there is some conflict with the updatepanels on your page..
Try removing all your Update Panels and try again.. It will work for sure.. Mine worked a few seconds ago.. so thought It would be good to share..

ASP.Net: Ajax registration question

I worked with: ASP.Net: Ajax check for registration as a user?
It has a few errors, I don't understand:
1) It worked only one time for one textbox. If the textbox is edited a second time, the breakpoint will not be hited. Why?
2) For my Email, I have a check, that there is no duplicate, when there is one, there should the set an error panel visible, but it don't show.
protected void txtEMail_TextChanged(object sender, EventArgs e)
{
Business.UserHandling uh = new Business.UserHandling();
if (uh.CheckIfEmailExists(txtEMail.Text))
{
panelHelp.Visible = true;
lblHelp.Text = "EMail existriert schon.";
}
}
When the update mode is conditional
<asp:scriptmanager runat="server" id="sm1" />
<asp:updatepanel runat="server" id="up1" updatemode="Conditional"> // here the updatemode is conditional ...
<contenttemplate>
<asp:textbox runat="server" id="tbUsername" autopostback="true" ontextchanged="tbUsername_TextChanged" />
<asp:customvalidator runat="server" text="Email already used" id="cusValEmail" />
<asp:textbox runat="server" id="tbPassword" />
</contenttemplate>
</asp:updatepanel>
You need to call
protected void txtEMail_TextChanged(object sender, EventArgs e)
{
Business.UserHandling uh = new Business.UserHandling();
if (uh.CheckIfEmailExists(txtEMail.Text))
{
panelHelp.Visible = true;
lblHelp.Text = "EMail existriert schon.";
}
up1.Update(); // call to update the update panel "up1"
}
Sorry I'm a bit rusty, it's a while since I've used update panels.
After an update panel updates you must reinitialise the javascript on the html elements inside it.
So, to the end of your method you could add:
protected void txtEMail_TextChanged(object sender, EventArgs e)
{
Business.UserHandling uh = new Business.UserHandling();
if (uh.CheckIfEmailExists(txtEMail.Text))
{
panelHelp.Visible = true;
lblHelp.Text = "EMail existriert schon.";
}
// Re-init javascript
ScriptManager.RegisterStartupScript(Type, String, "add onchange js here", Boolean);
}
see http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx

Resources