ASP.NET update labels separately and asynchronously - c#

Ok so I can successfully update my page labels asynchronously using a timer. The problem is that the labels always update simultaneously while I want each one to update in sequence.
Here is my aspx:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel runat="server" id="UpdatePanel1"
UpdateMode="Conditional">
<contenttemplate>
<asp:Timer id="Timer1" runat="server"
Interval="5000"
OnTick="Timer1_Tick">
</asp:Timer>
<asp:Label ID="Label1" runat="server" >Label1</asp:Label>
<asp:Label ID="Label2" runat="server" >Label2</asp:Label>
</contenttemplate>
</asp:UpdatePanel>
</asp:Content>
And my codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
public partial class _Default : Page
{
public int counter = 0;
protected void Timer1_Tick(object sender, EventArgs e)
{
counter++;
System.Diagnostics.Debug.WriteLine("Counter: " + counter);
if (counter == 1)
{
Label1.Text = "<font color='green'>Started</font>";
UpdatePanel1.Update();
}
if (counter == 2)
{
Label2.Text = "<font color='green'>Started</font>";
UpdatePanel1.Update();
}
}
}
After trying several examples I decided to ask here and see if I was missing something obvious. Somehow my counter variable is being reset to 0 which tells me that the entire page may be being rerun each tick instead of just the Timer1_Tick method.

The clause where counter == 1 also increments counter, so by the end of the clause, counter = 2, hence the other condition is also true.
Don't increment counter within the counter == 1 clause.

Related

Displaying Array Elements in an *.aspx page

For some of you, this may seem trivial - but please indulge me as I seem to have a severe mental block in understanding how displaying array elements is possible.
Ok, so here's where I'm at:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestCoding._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1><%: Title %>.</h1>
<h2>Modify this template to jump-start your ASP.NET application.</h2>
</hgroup>
<p>
<asp:TextBox ID="post_feedback" runat="server" Height="100" Width="500" BackColor="#0066FF" Font-Bold="True" ForeColor="#FF9933" Wrap="False" TextMode="MultiLine" BorderColor="#000099" BorderStyle="Groove" BorderWidth="2"></asp:TextBox>
<br />
<asp:Button ID="Count_Sentences" runat="server" Text="Count Sentences" OnClick="Count_Sentences_Click"/>
<br />
<br />
<asp:Label ID="Num_Sentences" runat="server" Font-Bold="true">How Many Sentences Do we have today?</asp:Label>
</p>
</div>
</section>
</asp:Content>
And the Default.aspx.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestCoding
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Count_Sentences_Click(object sender, EventArgs e)
{
int post_length = post_feedback.Text.Length;
string[] post_words = post_feedback.Text.Split(' ');
int num_words = post_words.Length;
Num_Sentences.Text = post_feedback.Text + " " + Convert.ToString(post_length) + " and has " + post_words.Length + " words." + post_words[0];
for (int i = 0; i < num_words; i++)
{
Console.WriteLine(post_words[i]);
}
}
}
}
Ok, so I understand that Num_Sentences is a Label I created in the aspx page - and that on clicking the button, the Count_Sentences_Click routine is called, it does some "stuff" and binds Num_Sentences.Text to a string that's comprised of different strings and other data...
The bit of code after that data binding, which I intend to have all the elements in the post_words array be written...but it's not working out so well.
What I have found so far it seems is, "Oh, all you have to do is set up a loop of sorts and just do Console.WriteLine(arrayname[i]) and all will be well with the universe."
Obviously, I am having some problems in understanding how to successfully display the array elements. Do I need a separate Label ID to put this into or what? I'm confused. :P

javascript textbox_changed value

here is my ASPX code
<%# Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="About.aspx.cs" Inherits="About" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script language="javascript" type="text/javascript">
function sum(t1)
{
var txt1 = document.getElementById('MainContent_TextBox2').value;
var result = parseInt(txt1) / 2;
var result1 = parseInt(result);
if (!isNaN(result))
{
document.getElementById(t1).value = result1;
}
}
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:TextBox ID="TextBox2" runat="server" onkeyup="sum('MainContent_TextBox3')"</asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server" ReadOnly="True"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"/>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
and my c# code is that
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class About : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox4.Text = TextBox3.Text;
}
}
the problem is that when i click on Button1 no error and TextBox4 is empty and i want that when i click on Button1 textbox3 value is transfered in textbox4.
It's because of the ReadOnly="True" that you have set on TextBox3.
When a control is set to ReadOnly in ASP.NET, the value that was placed into the control when the page was original rendered will not be updated.
Even if you change the value in the control on the browser (as you are doing), the value that is sent back to the server will not effect the value in the TextBox control - it will keep it's old value thanks to the ViewState.
The answer is to store the new value in a <asp:HiddenField>, which you should update at the same time as TextBox3.
Then on the server use the value in the hidden field, as that will contain the value you want. (Also, remember that you will need to update the value in the textbox from the hidden control as part of the postback).

Invalid postback or callback argument (HiddenField and container Visible=false)

I've not found answers that matched my circumstances, so I'm posting an answered question hoping it will help others.
I was getting the error
Invalid postback or callback argument. Event validation is enabled
using in configuration or <%#
Page EnableEventValidation="true" %> in a page. For security
purposes, this feature verifies that arguments to postback or callback
events originate from the server control that originally rendered
them. If the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument)
at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument)
at System.Web.UI.WebControls.HiddenField.LoadPostData(String postDataKey, NameValueCollection postCollection)
at System.Web.UI.WebControls.HiddenField.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection)
at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
I've got a Databound ListView (with a few 100s rows), with buttons on each row. The buttons bring a popup. The popup has dropdownlists and other controls doing asynchronous postbacks. I need to make sure I do asynchronous postbacks to avoid refreshing my big table.
I get the error when I click the button on one row, then change a dropdownlist inside the popup which fires a postback (selected item changed). Boom.
Here's the markup for a reduced sample, without popup and javascript at all! It still exhibits the problem. Click twice on a button in a row to get the error.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestPopupAsynchPostback.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scriptMgr" runat="server" ScriptMode="Debug" EnablePartialRendering="true"
EnableScriptGlobalization="true" EnableScriptLocalization="true" EnablePageMethods="true"/>
<asp:ObjectDataSource ID="ListDataSource" runat="server" SelectMethod="List" TypeName="TestPopupAsynchPostback.Default" />
<asp:Label runat="server" ID="PageLabel"></asp:Label>
<asp:ListView ID="EL" runat="server" DataSourceID="ListDataSource" OnItemDataBound="EntityList_OnItemDataBound">
<LayoutTemplate>
<table border="1">
<tr id="itemPlaceholder" runat="server" enableviewstate="false">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server" id="DefaultRow" enableviewstate="false">
<td>
<asp:Label ID="Lbl" runat="server" EnableViewState="false" />
</td>
<td>
<button runat="server" type="button" id="ReportingButton" enableviewstate="false" onserverclick="ReportingButton_OnClick" causesvalidation="false">click</button>
</td>
</tr>
<%-- Fix part 1: Change SpecialRow visible = true--%>
<tr runat="server" id="SpecialRow" visible="false" enableviewstate="false">
<td>
<asp:Label ID="Lbl2" runat="server" EnableViewState="false" />
<asp:HiddenField runat="server" ID="fn_hid" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
</form>
</body>
</html>
Here's the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace TestPopupAsynchPostback
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager sm = ScriptManager.GetCurrent(Page);
PageLabel.Text = DateTime.UtcNow.ToString() + " IsPostBack:" + IsPostBack + " IsInAsyncPostBack:" + (sm == null ? "" : sm.IsInAsyncPostBack.ToString());
}
protected override void Render(HtmlTextWriter writer)
{
ScriptManager sm = ScriptManager.GetCurrent(this.Page);
if (sm != null)
{
foreach (ListViewDataItem row in EL.Items)
{
HtmlButton reportingButton = row.FindControl("ReportingButton") as HtmlButton;
if (reportingButton != null)
sm.RegisterAsyncPostBackControl(reportingButton);
}
}
base.Render(writer);
}
public IList<string> List()
{
return (new string[] { "ONE", "TWO"}).ToList();
}
protected void ReportingButton_OnClick(object sender, EventArgs e)
{
//Do something useful here, for now, just a postback event
}
protected void EntityList_OnItemDataBound(object sender, ListViewItemEventArgs e)
{
Label lbl = e.Item.FindControl("Lbl") as Label;
Label lbl2 = e.Item.FindControl("Lbl2") as Label;
lbl.Text = lbl2.Text = e.Item.DataItem.ToString();
HtmlTableRow specialRow = e.Item.FindControl("SpecialRow") as HtmlTableRow;
if (e.Item.DataItemIndex%2 == 0)
{
HiddenField fn_hid = e.Item.FindControl("fn_hid") as HiddenField;
fn_hid.Value = "test1";
specialRow.Visible = true;
}
//Fix part 2: set SpecialRow Visible = false in code behind
//else
// specialRow.Visible = false;
}
}
}
I initially thought my javascript was at fault as I am modifying things with it. However, the process of creating a sample page has helped me find the problem.
It turns out it has nothing to do with the javascript or the popup. It's to do with a HiddenField contained inside a TR HtmlControl (asp.net server side control) with Visible=false IN THE MARKUP. I then use the code behind to set Visible=true when I need to in OnItemDataBound event.
This is what is causing the error for me: It seems that because the container (the TR SpecialRow) is Visible=false, I guess something is not rendered. I then come along in OnItemDataBound, decide that this row must be shown, and set Visible=true and set the value of my HiddenField. Boom.
If I remove the markup for the hidden field and don't set its value, no crash.
So it's not just the visibility of the TR on its own, it's the HiddenField too.
My fix: don't set Visible=false in the markup, and change OnItemDataBound to set Visible=false when required.
In other words: I was defaulting to hide things in markup and use code behind to show them. I changed this around and show things by default in markup and hide them using the code behind.
I've added the fix in the markup and code above.

The connection was reset in Upload Telerik

I code a example like telerik Upload demo but have the following error when submit(in FF):
The connection was reset.
The demo of telerik RadUpload is here
This is the code of .aspx file:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage1.master" AutoEventWireup="true" CodeFile="Upload.aspx.cs" Inherits="Main_Upload" %>
<%# Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
<title>Upload file</title>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<telerik:RadScriptManager ID="rsmScriptManager" runat="server">
</telerik:RadScriptManager>
<telerik:RadProgressManager ID="rpmUploadFile" runat="server" />
<div style=" color:Green">Valid files(*.doc, *.docx, *.xls, *.xlsx, *.pdf)</div>
<telerik:RadUpload ID="rulFiles" runat="server" InitialFileInputsCount="2" MaxFileInputsCount="5" AllowedFileExtensions=".doc,.docx,.xls,.xlsx,.pdf">
</telerik:RadUpload>
<telerik:RadProgressArea runat="server" ID="rpaUpload"></telerik:RadProgressArea>
<asp:Button ID="btnUpload" runat="server" Text="Ok" OnClick="btnUpload_Click" />
<br />
<asp:Label ID="lblNoResults" runat="server" Visible="True">No uploaded file!</asp:Label>
<asp:Repeater ID="rptValidResults" runat="server" Visible="false">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"FileName") %>(<%#DataBinder.Eval(Container.DataItem,"ContentLength").ToString() + " bytes" %>)<br />
</ItemTemplate>
</asp:Repeater>
<div style="color: red; padding-top: 40px;">Invalid files:</div>
<asp:Label id="lblNoInvalidResults" runat="server" Visible="True">No invalid files.</asp:Label>
<asp:Repeater ID="rptInvalidResults" runat="server" Visible="false">
<ItemTemplate>
File: <%#DataBinder.Eval(Container.DataItem,"FileName") %>(<%#DataBinder.Eval(Container.DataItem,"ContentLength").ToString() + " bytes" %>)<br />
Mime-type: <%#DataBinder.Eval(Container.DataItem,"ContentType") %>
</ItemTemplate>
</asp:Repeater>
And the code behind in *.cs file:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
public partial class Main_Upload : System.Web.UI.Page
{
protected void btnUpload_Click(object sender, EventArgs e)
{
BindValidResult();
BindInvalidResult();
}
private void BindValidResult()
{
if(rulFiles.UploadedFiles.Count > 0)
{
foreach (UploadedFile validFile in rulFiles.UploadedFiles)
{
var targetFolder = Server.MapPath(Commons.PAGER.UPLOAD_FOLDER);
validFile.SaveAs(Path.Combine(targetFolder,validFile.GetName()),true);
}
lblNoResults.Visible = false;
rptValidResults.Visible = true;
rptValidResults.DataSource = rulFiles.UploadedFiles;
rptValidResults.DataBind();
}
else
{
lblNoResults.Visible = true;
rptValidResults.Visible = false;
}
}
private void BindInvalidResult()
{
if(rulFiles.InvalidFiles.Count > 0)
{
lblNoInvalidResults.Visible = false;
rptInvalidResults.Visible = true;
rptInvalidResults.DataSource = rulFiles.InvalidFiles;
rptInvalidResults.DataBind();
}
else
{
lblNoInvalidResults.Visible = true;
rptInvalidResults.Visible = false;
}
}
}
Thanks!!!!
I'll go ahead and tell you with almost 100% certainty that the line that is causing this is:
var targetFolder = Server.MapPath(Commons.PAGER.UPLOAD_FOLDER);
It could be that you do not have permission to connect the server, or a variety of other issues.
To test this change "var targetFolder" to something like:
var targetFolder = #"C:\Users\j\Desktop\TEMP\"
Run this and it works perfectly, hence the idea that the path you're trying to access on the server is the problem.
Perhaps you should specify the path if possible. For example, if you are on a domain:
var targetFolder = #"\\server\Users\"
This would access that server and then the users folder therein that I have on my domain.

Problem with very simple ASP.NET 3.5 app, using C#

My problem is that I can only seem to click the button once, if I click multiple times it's like it's dead. Doesn't do anything. So if I click it once it sets the text to "Works". How come it doesn't keep alternating between values when I click many times?
I have the following C# code (I know I am using too many namespaces, but please disregard that);
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Security;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Click to test";
}
protected void Click(object sender, EventArgs e)
{
if (Label1.Text == "Works")
{
Label1.Text = "Try again";
}
else
{
Label1.Text = "Works";
}
}
}
And here is the ASPX code;
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Click" />
</form>
</body>
</html>
In your Page_Load you need to check IsPostBack If it is a postback you shouldn't set the control value.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Label1.Text = "Click to test";
}
Or in the case of an ajax update, it's IsAutoPostback (I think!)
The solution is what Sophie88 suggested, but I wanted to add some additional detail to explain exactly what's happening.
User initially requests page: (IsPostBack is false )
Aspx markup is parsed: Label1.Text is "Label"
Page_Load fires, sets Label1.Text to "Click to test"
User clicks button the first time: (IsPostBack is true)
Aspx markup is parsed: Label1.Text is "Label"
ViewState is restored, Label1.Text becomes "Click to test"
Page_Load runs, sets Label1.Text to "Click to test"
Click method runs. Label1.Text == "Click to test", so Label1.Text set to "Works"
User clicks button second time: (IsPostBack is true)
Aspx markup is parsed: Label1.Text is "Label"
ViewState is restored, Label1.Text becomes "Works"
Page_Load runs, sets Label1.Text to "Click to test"
Click method runs. Label1.Text == "Click to test", so Label1.Text set to "Works"
Why are you setting the Label1.Text in the page_load?
IN your markup, just set the Text property to "Click to test"
<asp:Label ID="Label1" runat="server" Text="Click to test"></asp:Label>
Each time you load the page you are setting the Label1.Text to "Click to test" (Page_Load happens every time the page is displayed), then the click event is triggered and correctly sees that the label isn't set to "Works" and so sets it to "Works".
How to fix it, see Sophie88's answer.

Categories

Resources