I have an UpdatePanel that displays the text, 'Please wait while the files are created...', when the user clicks the button 'Create Files'. Once the processing is completed, the text is updated to display 'Processing completed'. This works correctly.
What I want to do is add a processing image to the left of the text to show the user that the application is working. I have added the image. When I set the 'Visible' attribute to true, it displays as a spinning circle. What I want to do is display the image only when the text, 'Please wait while the files are created...'.
So initially, I set the image to, Visible-"false". I thought I could just add a line of code to the javascript that displays the text, 'Please wait..' but it is not displaying. Below is my code:
JavaScript:
script type="text/javascript">
$(document).ready(function () {
bindButton();
});
function bindButton() {
$('#<%=btnCreateFiles.ClientID%>').on('click', function () {
$('#<%=lblCaption.ClientID%>').html('Please wait while the label files are being created...');
//I thought I could just add this line and the image would at least display.
//But it does not display. I have also tried setting it to 'visible' and that
//doesn't work either.
// document.getElementById("<%=imgProcessing.ClientID%>").style.display='inline-block';
});
}
</script>
HTML:
<asp:UpdatePanel ID="ProgressUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Image ID="imgProcessing" runat="server" CssClass="floatleft" ImageUrl="~/Images/updateProgress.gif" Visible="false" />
<asp:Label ID="lblCaption" runat="server" CssClass="label" ForeColor="Red" Visible="true"></asp:Label>
<asp:Button ID="btnCreateFiles" runat="server" Text="Create Labels Files" Width="206px" CssClass="label" Height="37px" OnClick="btnCreateFiles_Click" style="float: right"/>
</ContentTemplate>
</asp:UpdatePanel>
This is the Code Behind that is in the Click event:
protected void btnCreateFiles_Click(object sender, EventArgs e)
{
string tstrIssueMonth = string.Empty;
string tstrFolderPath = string.Empty;
try
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(string), "bindButton", "bindButton();", true);
//do processing here
ProgressUpdatePanel.ContentTemplateContainer.Controls.Add(lblCaption);
ProgressUpdatePanel.Update();
lblCaption.ForeColor = Color.Green;
lblCaption.Text = "Processing completed...files have been created.";
}
}
So, I need to be able to show the processing image when the text, 'Please wait...' is shown and when the text 'Processing completed...' is shown the image is not visible.
How do I do that?
Thanks,
Related
I am now creating a web site with webforms in C#. I made a button that opens the child window with a landscape photo if pressed. On top of the landscape painting in the child window, comments written in the parent window are displayed.
The user can press this button to open as many child windows as they press, separate from the ASPX page with this button. Just press the button 10 times to open 10 pages of child windows with pictures of landscape paintings.
What I want to do is not press the button 10 times to create 10 child windows, but I want to update the child window 9 times after the child window is created in the first time.
If possible, I'd like you to tell me how to do it. Also, I thought that it would be difficult for me to do so, so I thought that if I pressed the button after the second time, the old child window created by pressing the button before that would close and a new child window would be born.
Below is the code I wrote.
↓aspx
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
↓aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string url=string.Format("WebForm1.aspx?q={0:s}",TextBox1.Text);
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(cstype, "OpenNewWindow", "window.open('" + url + "', null);",true);
}
The problem is twofold. One way is to update the child window. The other way is to close the child window. I thought that the line window would be closed with the code below, so I tried it lightly, but the parent window closed and the child window remained.
↓aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
string url=string.Format("WebForm1.aspx?q={0:s}",TextBox1.Text);
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(cstype, "CloseNewWindow", "window.Close('" + url + "', null);",true);
}
What should I do?
I think you best consider having this pop up appear on the CURRENT page.
And now that you want to restrict to "one", then that makes this a WHOLE lot less work.
There are more "dialog" systems then flavors of ice cream to choose from.
but, the two most common are the bootstrap ones, and the one from jQuery.UI.
I find the jQuery.UI VERY easy to work with - and you can control position with much greater ease then bootstrap ones.
And given that you have a SUPER high chance of already having jQuery, then adopting jQuery.UI from the same folks makes all the more sense.
And jQuery.UI dialogs can be "modal", and that means focus can't get out of the dialog until you "ok" or "save" or whatever.
So, lets take a simple GridView. Say we have some rows, and a "image".
When we click on the edit button, we pop a dialog with the picture, and also allow you to edit the comments.
So, our Grid is say this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
<asp:BoundField DataField="Fighter" HeaderText="Fighter" />
<asp:BoundField DataField="Engine" HeaderText="Engine" />
<asp:BoundField DataField="Thrust" HeaderText="Thrust" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:ImageButton ID="cmdView" runat="server" Width="150px"
ImageUrl = '<%# Eval("ImagePath") %>'
OnClick="cmdView_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code on page load is thus this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
SqlCommand cmdSQL = new SqlCommand("SELECT * FROM Fighters");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
And now we have this:
So, the way jQuery.UI works?
You create a simple "div" on the same page, and it will become your "dialog"
You then hide with style=display:none.
So our markup for this "div" to disaplay the picture "big" and edit comments is this
(we drop it below the GV)
So, we have this simple markup to display picture, and let user edit comments for the picture:
<div id="EditOne" runat="server" style="text-align:center;display:none" clientidmode="static">
<br />
<asp:Image ID="Image1" runat="server" width="90%" />
<br />
<h4>Edit Description</h4>
<asp:TextBox ID="txtDescription" runat="server"
TextMode="MultiLine" Columns="90" Height="100px">
</asp:TextBox>
<br />
</div>
<asp:Button ID="cmdSave" runat="server" Text="Save" ClientIDMode="Static"
style="display:none" OnClick="cmdSave_Click"/>
Note careful in above - right below the div, I have a hidden save button.
So, now the jQuery routine that we pop to display this div as a dialog:
this:
<script>
function popimage(btn) {
pWidth = "50%"
myDialog = $("#EditOne");
myDialog.dialog({
title: "Edit Comments",
modal: true,
width: pWidth,
closeText: "",
show: "fade",
buttons: {
Save: function () {
myDialog.dialog("close")
$('#cmdSave').click()
},
Cancel: function () {
myDialog.dialog("close")
}
}
})
}
</script>
So, now we only need our button row click from the grid (I used image button).
That code is this:
We get the current row PK id, pull from database, and fill out the "div", and then pop it:
protected void cmdView_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow gRow = (GridViewRow)btn.NamingContainer;
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM Fighters WHERE ID = #ID");
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PK;
DataTable rstFighter = MyRstP(cmdSQL);
Image1.ImageUrl = rstFighter.Rows[0]["ImagePath"].ToString();
txtDescription.Text = rstFighter.Rows[0]["Description"].ToString();
ViewState["rstFighter"] = rstFighter;
Page.ClientScript.RegisterStartupScript(
this.GetType(),"MyEdit","popimage()", true);
}
And now our save button, to send information back to database is this:
protected void cmdSave_Click(object sender, EventArgs e)
{
// Save comments (and other fields back to database)
DataTable rstFigher = (DataTable)ViewState["rstFighter"];
rstFigher.Rows[0]["Description"] = txtDescription.Text;
SaveData(rstFigher, "Fighters");
LoadGrid(); // refresh grid to show any edits
}
So, the results now look like this when I click on a row image:
Note how the web page behind goes "darker gray" and the pop up is model.
So, I would consider jQuery.UI dialogs.
And I did use two helper routines (after all, we don't write the same code over and over to get get a simple data table, right???).
Those two helper routines were:
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
void SaveData(DataTable rstData,string sTable)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM " + sTable, conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(rstData);
}
}
}
So, as above shows you have complete control over closing the pop up dialogue, but MUCH more important we can then also with ease update the current page to reflect those changes ( in our example update the description text in our pick list GridView). And with both the grid display and editing on the same page we also require much less code.
I'm trying to add an error label to the top of a panel I have. I have a button created in C# on page load that calls a JavaScript function that I want to display an error message on my panel when clicked.
C#:
private void CreateButton(int pID, string changeType)
{
ASPxButton btn = new ASPxButton();
btn.Text = "Execute Request";
btn.ID = "btn" + changeType;
btn.AutoPostBack = false;
btn.ClientSideEvents.Click = GetClientSideEventHandler(string.Format("OnProcessRequest(s, e, '{0}','{1}')", pID.ToString(), changeType));
TableRow oRow = new TableRow();
TableCell oCell = new TableCell();
oCell.CssClass = "table-cell";
oCell.Controls.Add(btn);
oRow.Cells.Add(oCell);
tblButtons.Rows.Add(oRow);
}
JS:
function OnProcessRequest$(pID, pChangeType) {
document.getElementById('errLabel').value = "Test";
}
ASPX:
<asp:Label ID="errLabel" runat="server"/>
When this code runs, it always throws the following error:
Error: Unable to set property 'value' of undefined or null reference.
I have tried also using:
document.getElementById('<%=errLabel.ClientID%>').value = "Test";
but this also throws the error.
How can I change the value of this label when this button is clicked in JS?
Ok, to change a asp.net label in JavaScript, you can do this:
(we assume you set the label client id mode>
So, if we have label on the page, you can do this:
<asp:Label ID="Label1" runat="server" Text="" ClientIDMode="Static"></asp:Label>
JavaScript to change above is this:
var lbl = document.getElementById('<%=Label1.ClientID%>');
lbl.innerText = "Js lable text changed";
Or
lbl.innerHTML = "<h2>this is some big text by js</h2>"
Be VERY careful with case, and VERY careful with extra spaces etc. in the get Element.
Also, do NOT forget to include the Text="" in your label!!!! (you are missing this!!!).
JavaScript is VERY flakey - one small wrong move, and it just rolls over and goes home. (and the debugger in browsers is on par with a trip to the dentist).
You can also use jQuery.
The above thus becomes this:
var lbl = $('#Label1');
lbl1.text("js jquery text change");
Now, lets do the same for a text box.
our asp.net text box:
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static" ></asp:TextBox>
JavaScript:
var txt = document.getElementById('<%=TextBox1.ClientID%>');
txt.value = "This is js text for text box";
And as jQuery:
var txt = $('#TextBox1');
txt.val("js jquery text for the text box");
So, for a asp.net label? You use innerText, or innerHTML.
(or text("your text here") with jQuery)
and with jQuery, you use .value without ()
Try adding ClientIDMode="Static" to your label if that property is available to you. Or you could add ClientID="errLabel" as an alternative. What's happening is asp.net will automatically give your field a generated id for closure on the client side so it will not match your id "errLabel".
<asp:Label runat="server" ID="errLabel" ClientIDMode="Static"></asp:Label>
OR
<asp:Label runat="server" ID="errLabel" ClientID="errLabel"></asp:Label>
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.control.clientidmode?view=netframework-4.8#System_Web_UI_Control_ClientIDMode
I'm trying to make an UI where, after uploading an image, the page must do a reload/postback without a TabContainer(ajaxcontroltoolkit) changing its ActiveTabIndex, but the default postback of the button(asp:button) causes me troubles when i try to realod the page via browser manually, it tries to re-do the last method used by the button if i don't use the next code (to reload the page):
Administrar.aspx.cs:
ScriptManager.RegisterStartupScript(this, this.GetType(), "key", "ShowMessage()", true);
JavaScript related function:
function ShowMessage()
{
alert('Exito al cargar imagen.');
window.location.href = 'Administrar.aspx';
}
BUT!, if i use this code when the page is reloading i loss the ActiveTabIndex.
All i want to do is, to keep an ActiveTabIndex when uploading an image to the database without having troubles with the browser manual reload, can you please tell me what i'm doing wrong or what can i do? i'm stuck on this for days.
here's the code for a better understanding:
FrontEnd:
<asp:TabContainer ID="TabContainer1" CssClass="cssTab" runat="server">
<asp:TabPanel runat="server" ID="TabPanel1" HeaderText="INFORMACIÓN">
<ContentTemplate>
<div class="divCNTRL1">...</div>
<div class="divDSPLY1">...</div>
</ContentTemplate>
</asp:TabPanel>
<asp:TabPanel runat="server" ID="TabPanel2" HeaderText="IMÁGENES">
<ContentTemplate>
<div class="divCNTRL2">
<h3>Agregar Imagenes</h3>
<label class="lbl">Relación:</label>
<asp:DropDownList CssClass="elementControl2" DataValueField="idInformacion" DataTextField="RelGal" ID="ddlRelacionGaleria" runat="server"></asp:DropDownList>
<label class="lbl">Imagen:
<asp:RequiredFieldValidator ValidationGroup="grpImg" ID="RequiredFieldValidator12" runat="server" ErrorMessage="*Imagen Invalida." ControlToValidate="FilUplIMG" ForeColor="#CC3300"></asp:RequiredFieldValidator>
</label>
<asp:FileUpload ID="FilUplIMG" runat="server" CssClass="elementControl2" />
<br />
<asp:Button runat="server" ID="btnAgrImg" OnClick="btnAgrImg_Click" CssClass="btnAgregarPropiedad" Text="AGREGAR" />
</div>
<div class="divDSPLY2">
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView runat="server" ID="gvImg" CssClass="gvImg2">...</asp:GridView>
<asp:Label ID="lblPage2" CssClass="lblPage" runat="server" ForeColor="Blue"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</ContentTemplate>
</asp:TabPanel>
</asp:TabContainer>
BackEnd(Just the button for adding):
public void btnAgrImg_Click(object sender, EventArgs e)
{
if (FilUplIMG.PostedFile != null)
{
string FileName = Path.GetFileName(FilUplIMG.PostedFile.FileName);
MySqlConnection con = new MySqlConnection(strConnString);
string strQuery = "insert into inmobiliarialrz.galeria (fkrelation, Relation, FileName, FilePath) values (#fkrelation, #Relation, #FileName, #FilePath)";
MySqlCommand cmd = new MySqlCommand(strQuery);
if (File.Exists(Server.MapPath("~/ImagenesPROP/") + FileName))
{
string script = "alert(\"Ya existe esta imagen.\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
}
else
{
//save files in the disk
FilUplIMG.SaveAs(Server.MapPath("~/ImagenesPROP/" + FileName));
cmd.Connection = con;
cmd.Parameters.AddWithValue("#fkrelation", ddlRelacionGaleria.SelectedValue);
cmd.Parameters.AddWithValue("#Relation", ddlRelacionGaleria.SelectedItem.Text);
cmd.Parameters.AddWithValue("#FileName", FileName);
cmd.Parameters.AddWithValue("#FilePath", "~/ImagenesPROP/" + FileName);
cmd.CommandType = CommandType.Text;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
lblFail.Visible = true;
lblFail.Text = ex.Message;
}
finally
{
con.Close();
con.Dispose();
}
this.MostrarImagen2();//this is a method to show data in a gridview.
lblFail.Text = "";
ScriptManager.RegisterStartupScript(this, this.GetType(), "key", "ShowMessage()", true);
TabContainer1.ActiveTabIndex = 1;//here i'm trying a desperate move.
}
}
}
I have 2 pages in asp.net with c# .
a parent.aspx and popup.aspx.
I passed a querystring(id) into page load of popup.aspx and used function to call row of table base on id and show gridview on popup.aspx.
now I want to select this row, and pass details into text boxes of parent.aspx that is open now.
Everything is ok and row of table is passed into text boxes, but it is into new window popup of parent.aspx page, that I don't want this.
I want pass details into this page(parent.aspx) that now is open.
How can I do that.thanks.
below is my code for pass id to pop-up window
protected void btn_search_id_Click(object sender, ImageClickEventArgs e)
{
string str1 = Encrypt(txt_sh_p.Text);
btn_search_id.Attributes.Add("onclick", "window.open('popup.aspx?sh_p_=" + str1 + "','Report','width=750,height=500,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,left=200,top=50'); return false;");
}
my code for reading id and select row and display row in gridview on page load event of popup.aspx:
protected void Page_Load(object sender, EventArgs e)
{
DAL.Sab_Ashkh sabt_ashkh = new DAL.Sab_Ashkh();
List<DAL.Sab_Ashkh> sabt_ashkh_list;
sabt_ashkh.sh_p = Decrypt(Request.QueryString["sh_p_"]);
sabt_ashkh_list = sabt_ashkhDB.GetShakh_find(sabt_ashkh.sh_p);
grid_ashkh.Visible = true;
grid_ashkh.DataSource = grid_ashkh_list;
grid_ashkh.DataBind();
}
and html code for pass row to parent page:
<Columns>
<asp:HyperLinkField DataTextField="id_shakh" DataNavigateUrlFields="id_shakh" DataNavigateUrlFormatString="parent.aspx?id_shakh={0}"
HeaderText="id" ItemStyle-Width = "150" />
<asp:TemplateField HeaderText="select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width = "150px" DataField = "sh_p" HeaderText ="kod"
>
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
</Columns>
I am just telling you how you can change the variable in Main page in popup page like:
Suppose Parent.aspx have:
<script type="text/javascript">
var items =[];
</script>
and in popup.aspx you can do something like :
window.opener.items.push(yourSelectedRows);
but as another workaround you can also use local storage like:
localStorage.setItem("selectedRecords", JSON.stringify(selectedRows));
suppose selectedRows are your array of object or anything else but as my experience the selectedRecords would be accessible in all HTML pages.
hope this help you.
Hi Aria Thanks for reply. I pass id by query string into popup window and show gridview . and this script for popup win :
<script type="text/javascript">
function SetName() {
if (window.opener != null && !window.opener.closed) {
var txtName = window.opener.document.getElementById("txt_id_mah");
grid = document.getElementById("grid_ashkh");
var cellPivot;
if (grid.rows.length > 0) {
for (i = 1; i < grid.rows.length; i++) {
cellPivot = grid.rows[i].cells[1];
TXT.value = cellPivot;
}
}
}
window.close();
}
</script>
but does not work.
I have seen some post regarding this question but i cannot find a solution for my problem. I have a text box and through autocompleteextender i am searching records from database. which works fine.
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" CombineScripts="false">
</ajaxToolkit:ToolkitScriptManager>
<asp:TextBox ID="txtAccNo" runat="server" Width="125px" ToolTip="Account Number">
</asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender2" runat="server"
TargetControlID="txtAccNo" MinimumPrefixLength="2" EnableCaching="true" CompletionSetCount="10"
CompletionInterval="1000" CompletionListCssClass="autoExtender" CompletionListItemCssClass="autoExtenderList"
ServiceMethod="getAccountNumbers" ServicePath="WebServiceGetAccounts.asmx">
</asp:AutoCompleteExtender>
Now i want to show some loading gif(http://loadinggif.com/images/image-selection/3.gif) in textbox when webservice searches for data. For that i want javascript function to load this gif in textbox. and when webservice shows some data i want to remove this gif. In addition i want to load this gif if user puts atleast 2 numbers in textbox. as MinimumPrefixLength property of autocompleteextender is set to 2. if Anyone can help? i will be very thankful.
Hope below solution/logic help you out.
<asp:TextBox ID="txtAccNo" runat="server" Width="125px" onchange="return inputText_Changed();" ToolTip="Account Number"> </asp:TextBox>
<script type="text/javascript">
function inputText_Changed() {
var accountNo = document.getElementById('<%= txtAccNo.ClientID %>').value.trim();
//check minimum input characters MinimumPrefixLength
if (accountNo.length >= 2) {
// remove / hide your gif image
return true;
}
else {
// Add / show your gif image
return false;
}
}
</script> `
Let me know if any query you have
Thanks
Happy Coding
there are some properties of AutoCompleteExtender like OnClientPopulating and OnClientCompleted... use those properties to perform any task. in my case i wanted to load a gif. i created a css class and a javascript function to load gif while using properties of AutoCompleteExtender.
onclienthiding="OnClientCompleted" onclientpopulated="OnClientCompleted"
JavaScript Function:
function OnClientPopulating(sender, e) {
sender._element.className = "loading";
}
function OnClientCompleted(sender, e) {
sender._element.className = "";
}
CSS Class:
.loading
{
background-image: url(img/loading.gif);
background-position: right;
background-repeat: no-repeat;
}