update textbox from code behind - c#

I'm in the process of converting an application into an ASP.NET Website. The way the page works is that the user puts in a list of machines in the box then click start, it goes through the list runs the checks and outputs the status and results to a text box on the left. In addition it puts a processing icon beside the check mark as it runs a check and removes it when the check is done. In my .NET application it works fine, but I can't figure out how to do it in ASP.NET
I've tried using Ajax controls to do this so I enclosed the status box in an update panel and put a timer that updates the panel every second.
In the code behind, right now I have a function that just rights out some test text to the results text panel, along with a 3 second pause to simulate the code in the back ground. However it doesn't update the panel until the function finishes instead of each time the text is updated.
In classic ASP I would have written the status out to either a text file or a DB and just set the page to reload on a regular basis and retrieve the information until done flag was hit and then stop the reloads. I was trying to avoid making all those call backs if I could help it. I was hoping there was a better way to do it, but if there isn't I could make just the update panel call back but I'm still not entirely sure how to turn the processing icons on and off.
Page Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>
<!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="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<table class="Standard">
<tr>
<td colspan="2">
<div class="Title">
Title
</div>
</td>
</tr>
<tr>
<td class="Column1">
<div style="text-align: center;">
Input Devices to Check<br />
<br />
<asp:TextBox ID="txtMachineList" runat="server" TextMode="MultiLine" Rows="12"
Width="200px"></asp:TextBox>
<asp:Button ID="btnStart" CssClass="button_blue_small" runat="server" Text="Start" OnClick="StartCheck" /><br />
<br />
</div>
<table>
<tr>
<td>
<asp:CheckBox runat="server" ID="chkOne" Text="Check 1" />
</td>
<td>
<asp:Image ID="Load1" runat="server" ImageUrl="Images/flower-loader.gif" Visible="false" />
</td>
</tr>
<tr>
<td>
<asp:CheckBox runat="server" ID="chkTwo" Text="Check 2" />
</td>
<td>
<asp:Image ID="Load2" runat="server" ImageUrl="Images/flower-loader.gif" Visible="false" />
</td>
</tr>
</table>
</td>
<td class="Column2">Status:<br />
<asp:UpdatePanel ID="StatusPanel" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="StatusPanelTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:TextBox ID="txtStatus" runat="server" Columns="300" Enabled="True" ReadOnly="True"
Width="800px" TextMode="MultiLine" Rows="35"></asp:TextBox>
<asp:Timer ID="StatusPanelTimer" runat="server" Interval="1000" OnTick="StatusTimer_Tick"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
}
protected void StartCheck(object sender,EventArgs e)
{
Load1.Visible = true;
Load2.Visible = true;
txtStatus.Text = "Test 1";
System.Threading.Thread.Sleep(3000);
txtStatus.Text += "Test 2";
System.Threading.Thread.Sleep(3000);
txtStatus.Text += "Test 3";
System.Threading.Thread.Sleep(3000);
Load1.Visible = false;
Load2.Visible = false;
}
protected void StatusTimer_Tick(object sender, EventArgs e)
{
StatusPanel.Update();
}

So it seems the problem is in your "Start" button's function.
If you just add:
txtStatus.Text += "Tick\n";
to your tick event, you can see that your page is updating.
The problem is that After you click the button, the page doesn't receive a response until the StartCheck function finishes (Even the ticking stops).

Related

Enabling a button on AsyncFileUpload upload complete

This is the scenario : I have a screen that has a AsyncFileUpload and a button on it. Now the problem is that an error pops up if the user clicks the button before the file is finished uploading so what I want to achieve is to disable the button on page load and as soon as the file's upload is complete it has to make the button visible again. Now I've went through problems and solutions on the web and what I could make out is that the button is processed on the server side so I can't use javascript to do this. So when I do it in the code behind of the screen it disables the button successfully but it doesn't enable it successfully after the file upload is complete. The assumption that I have is because that no postback takes place and the button does not appear to be enabled because no screen refresh has taken place.
How do I get past this and how do I get that button to enable after the file upload is complete?
Here is what I have so far, it isn't much code but here it is anyway:
BulkInsert.aspx
<%# Page AspCompat="true" Title="MainPage" MasterPageFile="~/MasterPage.master" Language="C#"
AutoEventWireup="true" CodeFile="InventoryBulkInsert.aspx.cs" Inherits="content_inventory_InventoryBulkInsert" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<table border="0" class="tablebody" width="100%">
<tr>
<td class="title" colspan="2">
Bulk insert
</td>
</tr>
<tr>
<td class="headercell" colspan="2">
File Upload
</td>
</tr>
<tr>
<td class="style1">
File
</td>
<td class="style2" style="height: 26px">
<asp:AsyncFileUpload ID="AsyncUpload" runat="server" OnUploadedComplete="AsyncUpload_UploadedComplete"
OnClientUploadComplete="UploadComplete" OnUploadedFileError="AsyncUpload_UploadedFileError"
colspan="1" />
</td>
</tr>
<tr>
<td class="style1">
</td>
<td align="left">
<asp:Button runat="server" ID="btnImport" Text="Import" BackColor="#990000" ForeColor="White"
nowrap Width="214px" OnClick="btnImport_Click" />
</td>
</tr>
BulkInsert.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.btnImport.Enabled = false;
}
}
protected void AsyncUpload_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
this.btnImport.Enabled = true;
}
I would suggest using javascript only for showing the button, you will not use it in processing. You can use the AjaxFileUpload OnClientUploadComplete="UploadComplete" which is already included in your design, it would achieve your goal perfectly.
Create the function like this in markup:
function UploadComplete(sender, args) {
var control = document.getElementById("<%=btnImport.ClientID%>");
control.style.display = "block";
}
</script>
And then modify your button to have style="display:none"

Update panel in master page and asp fileupload in child page

i'm facing a problem, currently i'm having a update panel in my master page and in one of my child page i'm having a asp fileupload control.
My update Panel in master p[age:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:updateprogress associatedupdatepanelid="UpdatePanel1"
id="updateProgress" runat="server">
<progresstemplate>
<div id="processMessage" style=" background-image:url('../../Styles/ajax-loader3.gif'); width:100px; height:100px; background-repeat:no-repeat; background-position:center;">
</div>
</progresstemplate>
</asp:updateprogress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
..
</ContentTemplate>
</asp:UpdatePanel>
</form>
My Child page which needs a fileupload:
<div id="Annoucments" class="ContentDIV">
<h2 class="Tabheader">Annoucments</h2>
<p class="tabdescription">Here you will be able to upload announcements and pictures to be displayed in the login page, below is the current announcement click on update to save the changes that you have made.</p>
<table width = "100%">
<tr>
<td class="Tablabel">Annoucment title:</td> <td class="tableInput" align="left"><asp:TextBox ID="Announcement_TB" runat="server" CssClass="textboxTabs"></asp:TextBox></td>
<td class="Tablabel">Picture/Poster:</td> <td class="tableInput" align="left"><asp:FileUpload ID="Announcement_PIC" runat="server" CssClass="textboxTabsFiles"/></td>
</tr>
<tr>
<td class="Tablabel">Description:</td> <td class="tableInput" align="left"><asp:TextBox ID="Announcement_Desc" CssClass="textboxTabs" runat="server" Rows="3" TextMode="MultiLine"></asp:TextBox></td>
</tr>
<tr><td colspan="4" style="height:10px" id ="BLANK">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</td></tr>
<tr>
<td colspan="2" align="right"><input type="button" id="Announcement_Update" runat="server" value="Update" class="TabButton" onserverclick="ANNOUNCEMENT_UPDATE_Click" style=" font-size:smaller"/></td><td colspan="2"> <input type="button" ID="ANNOUNCEMENT_Cancel" runat="server" value="Cancel" class="TabButton" style=" font-size:smaller"/></td>
</tr>
</table>
</div>
*When i click the button Announcement_Update backend codes will be triggered to get my filename, the file name returned will always be "" found out while debugging.*
Put this code in child page, to pass PostBackTrigger for file upload.
protected void Page_Load(object sender, EventArgs e)
{
UpdatePanel updatePanel = Page.Master.FindControl("UpdatePanel1") as UpdatePanel;
UpdatePanelControlTrigger trigger = new PostBackTrigger();
trigger.ControlID = Announcement_Update.UniqueID;
updatePanel.Triggers.Add(trigger);
}
enjoy coding :)
You can't get filename inside that UpdatePanel
either remove that UpdatePanel from your code or use Asynchronous File Uploader,
Alternatively you could use Ajax File Uploading techniques this is a little tricky though.
Asp UpdatePanel not work inside a update panel duw to postback issue.
You can add trigger with the button assosiated with uploader like
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Click" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
It works for me if you add the Trigger, but also make sure to edit to form tag to include:
<form runat="server" enctype="multipart/form-data">

ASP.Net Button not raising postback

I've a simple page in one of our web applications, which has the following markup:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="NewUpload.aspx.cs" Inherits="Mass_Upload.NewUpload" MasterPageFile="~/Master" Title="Document Mass Upload" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<link rel="Stylesheet" type="text/css" href="./../CSS/ScrollingTable.css" />
<script type="text/javascript" src="../Help/HelpPopup.js" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="CenterH1" runat="server">
Document Mass Upload <img style="Border:None;" src="../Help/help_icon.gif" />
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="CenterBody" runat="server">
<h3>Add New Upload</h3>
<table class="list">
<tr>
<td class="label" style="text-align:right;">Local File:</td>
<td class="normal">
<asp:FileUpload ID="fuFilename" runat="server" Width="405" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" Text="*"
ErrorMessage="A file to upload is required"
Display="Dynamic"
ControlToValidate="fuFilename"
ValidationGroup="DocumentUpload"
runat="server" />
</td>
</tr>
<tr>
<td class="label" style="text-align:right;">Document Description:</td>
<td class="normal">
<asp:TextBox ID="txtDescription" runat="server" Width="405" MaxLength="50" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" Text="*"
ErrorMessage="Document Description is a required field"
Display="Dynamic"
ControlToValidate="txtDescription"
ValidationGroup="DocumentUpload"
runat="server" />
</td>
</tr>
<tr>
<td class="label" style="text-align:right;">Document Type:</td>
<td class="normal">
<asp:DropDownList ID="ddDocType" runat="server" Width="405"/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" Text="*"
ErrorMessage="Document Type is a required field"
Display="Dynamic"
ControlToValidate="ddDocType"
ValidationGroup="DocumentUpload"
runat="server" />
</td>
</tr>
<tr>
<td class="label" style="vertical-align:top;text-align:right;">Customer Types:</td>
<td class="normal">
<asp:Label ID="lblSingleCustomer" Text="Specific Code:" runat="server" /><asp:TextBox ID="txtSingleCustomer" runat="server" Width="100px" /><br />
<asp:CheckBoxList ID="cblCustomerTypes" runat="server" Width="405px" RepeatDirection="Horizontal" RepeatColumns="5" RepeatLayout="Table" CellPadding="10" CellSpacing="0" />
</td>
</tr>
<tr>
<td class="normal" colspan="2"> </td>
</tr>
<tr>
<td class="normal" colspan="2"><asp:Label ID="lblError" runat="server" Text="" ForeColor="Red"/></td>
</tr>
<tr>
<td class="normal" colspan="2">
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="BtnCancel_Click" CssClass="medium" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="BtnUpload_Click" CssClass="medium" />
</td>
</tr>
</table>
</asp:Content>
It USED to work fine, but now, and without apparent change to code/design, both the "Upload" and "Cancel" buttons no longer work.
Putting a breakpoint in the codebehind's Page_Load() method shows that it is only called when the page is initially loaded, and not when the button is pressed.
Similarly, putting a breakpoint in the "BtnUpload_Click" event shows it is never called.
This is now not working both on my own development machine AND on the client's server (both when browsing to the servers page from my machine AND from the server itself).
It's important to stress that, between this working and it now not working, I am 90% sure nothing has changed in regards to the code.
Any help would be greatly appreciated, as the customer is rightly anxious - and i'm clueless as to what's causing it!
EDIT #1
Here's the codebehind for one of the buttons:
protected void BtnUpload_Click(object sender, EventArgs e)
{
if (DataAccess.CheckIfMassUploadAlreadyExists(fuFilename.FileName))
{
lblError.Text = "A file with the specified name already exists within the system.";
return;
}
else
{
try
{
UploadFile();
}
catch(Exception ex)
{
lblError.Text = ex.Message;// +"\nUsername:" + System.Web.HttpContext.Current.User.Identity.Name;
return;
}
}
}
.
Here's the reason.. and it's a really annoying reason too!
THIS:
<script type="text/javascript" src="../Help/HelpPopup.js" />
Should be THIS:
<script type="text/javascript" src="../Help/HelpPopup.js"></script>
Whoever decided the script tag needs to be treated differently to every other HTML tag, needs to be locked in a room with Justin Bieber.
First off all you should check your Validators and perhabs, comment them out for a test.
Is it possible that there are JavaScript-Errors showing on your page?
An ASP-Button is calling a JavaScript-Funktion (WebForm_DoPostBackWithOptions), if there is a JavaScript-Error "before" this line, sometimes you can't press a button.
apparently a client side "return false" is preventing the callback, this could be one of two reasons:
1-the validators always return not valid
2-some client script being called on the button returns false;
At the risk of being down voted for posting an answer to the title question which does not appear to be the OP's problem... I will offer this suggestion which fixed my similar problem:
<body background="images/GlobeBg.png" bgproperties="fixed">
</body>
Problem is, 'bgproperties' is NOT a valid attribute name even though some guys on the internet said it was. Other than an unnoticed squiggle underline in VWD 2008 Express, no error was emitted and the page otherwise looked normal. Simply, the update button and other input controls didn't work.
The cause for this for me was that a validator on another view in the same page was being fired, due to it being apart of the same validation group.So this prevented the post back.

Allow Enter key to login in asp.net?

I have a standard asp:login control:
<asp:Login ID="mbLogin" runat="server" TitleText=""
DestinationPageUrl="~/Default.aspx"
PasswordRecoveryText="Forgot your password?"
PasswordRecoveryUrl="~/LostPassword.aspx"></asp:Login>
In Internet Explorer, pressing Enter does not submit the form, but IE beeps at me 10 times rapidly. In other browsers Enter works perfectly fine and submits the forum as you'd expect.
I've seen this question but that only works when you have actual form element with an actual button, not the login control as a whole.
Why is it being blocked in IE (and why 10 times for some reason)? Is there a workaround?
In the designer of your Login control: "Convert To Template". Then in the Page Load set the defaultButton of your form by finding the LoginButton.
ASPX:
<form id="form1" runat="server">
<div>
<asp:Login ID="Login1" runat="server" OnAuthenticate="Login1_Authenticate">
<LayoutTemplate>
<table border="0" cellpadding="1" cellspacing="0" style="border-collapse: collapse;">
<tr>
<td>
<table border="0" cellpadding="0">
.....
<tr>
<td align="right" colspan="2">
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="Login1" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
</asp:Login>
</div>
</form>
Code-Behind:
protected void Page_Load(object sender, EventArgs e)
{
Button lbButton = Login1.FindControl("LoginButton") as Button;
form1.DefaultButton = lbButton.UniqueID;
}
This is a hack, but it will provide a work around for your issue with Internet Explorer.
Add a text box to your page that is hidden from view.
<!-- Hack for Internet Explorer browsers to allow the page to post back when the enter key is pressed-->
<asp:TextBox ID="txtIEHackBox" runat="server" style="visibility: hidden; display: none;" />
This will cause Internet Explorer to send back the Button Web control's name/value pair upon hitting Enter.
Button lbButton = Login1.FindControl("LoginButton") as Button;
ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
contentPlaceHolder.Page.Form.DefaultButton = lbButton.UniqueID;
I know this is a super old post, but another way to do this is by using an asp:Panel with DefaultButton set to the ID of the button that the user would normally click on to log in:
<asp:Login ID="LoginUser" runat="server">
<LayoutTemplate>
<asp:Panel ID="LoginPanel" runat="server" DefaultButton="LoginButton">
<other stuff here like username and password textboxes>
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In"/>
</asp:Panel>
</LayoutTemplate>

Asp.net Ajax problem

I installed the Asp.net Ajax toolkit. In my site I use the NummericUpDown from that toolkit.
Now, I want that a label changes when the NummericUpDown Textboxes changes. I try to use JavaScript for this, but I always get the following error:
'ASP.orders_aspx' does not contain a definition for 'changeAmount' and no extension method 'changeAmount' accepting a first argument of type 'ASP.orders_aspx' could be found (are you missing a using directive or an assembly reference?)
This is my code:
<%# Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
CodeFile="orders.aspx.cs" Inherits="orders" Title="the BookStore" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<script type="text/javascript">
function changeAmount()
{
var amount = document.getElementById("txtCount");
var total = 10 * amount.value;
document.getElementById("lblPrice").value = total;
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
<h1 id="H1" runat="server">
Bestellen</h1>
<asp:Panel ID="pnlZoeken" runat="server" Visible="true">
<asp:ObjectDataSource ID="objdsSelectedBooks" runat="server" OnSelecting="objdsSelectedBooks_Selecting"
TypeName="DAL.BooksDAL"></asp:ObjectDataSource>
<h3>
Overzicht van het gekozen boek</h3>
<asp:FormView ID="fvBestelBoek" runat="server" Width="650">
<ItemTemplate>
<h3>
Aantal boeken bestellen</h3>
<table width="650">
<tr class="txtBox">
<td>
Boek
</td>
<td>
Prijs
</td>
<td>
Aantal
</td>
<td>
Korting
</td>
<td>
Totale Prijs
</td>
</tr>
<tr>
<td>
<%# Eval("TITLE") %>
</td>
<td>
<asp:Label ID="lblPrice" runat="server" Text='<%# Eval("PRICE") %>' />
</td>
<td>
<asp:TextBox OnTextChanged="changeAmount()" ID="txtCount" runat="server"></asp:TextBox>
<ajaxToolkit:NumericUpDownExtender ID="NumericUpDownExtender1" runat="server" TargetControlID="txtCount"
Width="50" Minimum="1" ServiceDownMethod="" ServiceUpMethod="" />
</td>
<td>
-
</td>
<td>
<asp:Label ID="lblAmount" runat="server" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:FormView>
<asp:Button ID="btnBestel" runat="server" CssClass="btn" Text="Bestel" OnClick="btnBestel_Click1" />
<asp:Button ID="btnReChoose" runat="server" CssClass="btnDelete" Text="Kies een ander boek"
OnClick="btnRechoose_Click" />
</asp:Panel>
</asp:Content>
Does anyone know the answer?
Thanks a lot, Vincent
You're trying to assign a client-side method to the OnTextChanged event, which is a server-side event.
Also, your javascript is referencing the server id of the label and textbox. The WinForms engine appends characters to this depending where the control is nested. Use <%=myControl.ClientID%> to get around this.
You need to use some pure Javascript for this:
window.onload=function(){
//assign client method to textbox
document.getElementById('<%=txtCount.ClientID%>').onChange = function(){
var amount = document.getElementById('<%=txtCount.ClientID%>');
var total = 10 * amount.value;
document.getElementById('<%=lblPrice.ClientID%>').value = total;
}
}
Place that on your page instead of your current Javascript and get rid of the OnTextChanged="changeAmount()" attribute.
You set OnTextChanged for TextBox. It is refer to server method, that is fired on PostBack.
If you want to handle Up and Down events in background by method on your Page, you have to set
properties ServiceUpPath and ServiceUpMethod for NumericUpDown tag.
If you want to handle client events - set custom Up and Down buttons and set property OnClientClick to them.
See
http://www.asp.net/AJAX/AjaxControlToolkit/Samples/NumericUpDown/NumericUpDown.aspx

Categories