Unable to Update label Outside Update Panel - c#

I have spent lot of time to investigate how to update label outside Update panel. And finally found something but it does not update label. It works fine if we refresh the page. Please let me know error in code or any new way of doing this. Please find my code below. I think need add some more code for script manager Or dataItem()
Thank you guys for reply!
Code behind file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class scriptMgr : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void timer_Tick(object sender, EventArgs e)
{
if (ScriptManager1.IsInAsyncPostBack)
{
ScriptManager1.RegisterDataItem(Label3, "Hi");
}
}
}
}
Aspx page
<div>
<asp:Label ID="Label3" runat="server" Text="krwelkr"></asp:Label>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript" language="javascript">
enter code here
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(PageLoadingHandler);
function PageLoadingHandler(sender, args) {
var dataItems = args.get_dataItems();
if ($get('Label3') != null)
$get('Label3').innerHTML = dataItems['Label3'];
}
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
</div>

If you need to update the label with dynamic content from the server, have it wrapped in the same updatepanel or another updatepanel.
If the Label text is not dynamic, you could probably use JS to alter the label before firing the right event.
Also, UpdatePanels do "cause postbacks". its just that you don't notice them.
Or you can do this way:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode=Conditional>
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>
Code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Updated";
}

You need to use the pageLoaded event of the PageRequestManager.
The pageLoading event is raised before any content on the page is updated. So your changes made in pageLoading event will be lost if you also make changes to label's content anywhere else.
Therefore, when using the pageLoaded event which is raised after all content on the page is refreshed as a result of either a synchronous or an asynchronous postback, chnages made inside this event will overwrite all changes made anywhere else and will be the final.
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(PageLoadedHandler)
function PageLoadedHandler(sender, args) {
var dataItems = args.get_dataItems();
if ($get('Label3') != null)
// set Label3 to your actual values. You can test/debug by adding
// any test value
$get('Label3').innerHTML = "TTTTestingggg";
}
</script>

Add the register script in code behind event,
protected void timer_Tick(object sender, EventArgs e)
{
if (ScriptManager1.IsInAsyncPostBack)
{
//ScriptManager1.RegisterDataItem(Label3, "Hi");
ScriptManager.RegisterStartupScript(this, this.GetType(), "setLabelOrAnyName", "jQuery(function($) { $('#Label3').text('Whatever')});", true);
}
}
This should work.
Incase if you are not using jQuery library replace code with simple javascript.

Related

Calling div run at server from backend not working with update panel?

I built the search logic with textbox search. However, While I search and the query is being executed I want the spinner to run while the results are fetched.
Here's my code : -
I tried both way but the spinner does not show.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ClientIDMode="Inherit" UpdateMode="Always">
<ContentTemplate>
<asp:TextBox runat="server" ID="Searchtext" OnTextChanged="Searchtext_TextChanged" AutoPostBack="true"></asp:TextBox>
<div id="spinner" runat="server">
<img src="././spinner.gif/>
<div>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function show()
{
$('#spinner').css("display", "block");
}
</script>
protected void Searchtext_TextChanged(object sender, EventArgs e)
{
spinner.Visible = true;
searchLogic();
spinner.Visible = false;
}
Other way : -
<div id="spinner" style="display:none;">
<img src="././spinner.gif/>
<div>
public void searchLogic()
{
sqlLogic(); // Queries and Results
}
protected void Searchtext_TextChanged(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "MyFunction", "show()", true);
searchLogic();
}
If I set run at server or not, when I search it shows waiting in chrome. But spinner is not fired. What I am doing wrong?
I realized that the best way to solve it using Asp:UpdateProgress and I solved it.
Thanks op's.

How to find a client side element in an update panel from code behind?

While developing a user control in asp.net I found major difficulty to
find html client side element positioned within an update panel.
The .ascx side contains this:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="<%=ClientID%>_MyElement">
</div>
</ContentTemplate>
</asp:UpdatePanel>
And I need to get a reference to that div in my code-behind.
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
//var c = UpdatePanel1.FindControl("<%=ClientID%>_MyElement"); //<-not working.
//:
//get some values from c
//:
}
}
Now, since there is also Ajax (JavaScript) manipulating that div:
I cannot set runat="server" for that div.
I must use <%=ClientID%>_MyElement as id'ing convention.
So assuming the div is going to stay as it is - is there any way to fetch reference
to it from the code behind?
Try this:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="MyElement" runat="server">
</div>
</ContentTemplate>
</asp:UpdatePanel>
in code behind
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
var c = MyElement;
}
}
in javascript
var MyElement=document.getElementById('<%= MyElement.ClientID');
Try to access your div from your UpdatePanel. Example: var div = UpdatePanel1.Controls[0];

Ajax update panel causes blank space

I made an updatepanel to update a part of my code which uses a literal text to display html codes. I'm not sure why but when i use the same code on Page_Load, it came out funky.
protected void Page_Load(object sender, EventArgs e)
{
//Bind Staff Monitor Filter
filterLiteral.Text = PortalClass.getStaffFilter();
//Bind Staff Filter Data
loginPoolLiteral.Text = PortalClass.getLoginPoolData();
}
The original intent was for it to look like:
But the postback causes a blank space and my tags, (All, HTC Department etc) to instead of filtering the picture, brings me to the top of the page:
Here is my code for default.aspx:
<asp:UpdatePanel ID="UpdatePanelCrowdMonitor" runat="server"
RenderMode="Inline">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
//Some html codes
<asp:Literal ID="filterLiteral" runat="server"></asp:Literal>
<asp:Literal ID="loginPoolLiteral" runat="server"></asp:Literal>
</ContentTemplate>
</asp:UpdatePanel>
And my Default.aspx.cs:
protected void Unnamed1_Tick(object sender, EventArgs e)
{
//Bind Staff Monitor Filter
filterLiteral.Text = PortalClass.getStaffFilter();
//Bind Staff Filter Data
loginPoolLiteral.Text = PortalClass.getLoginPoolData();
}

Scriptmanager on one page, but the Panel on another

Im having a .Master page with
<asp:ScriptManager ID="ScriptManager" runat="server" />
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<ContentTemplate>
<asp:ContentPlaceHolder ID="MasterIndhold_Member" runat="server">
</asp:ContentPlaceHolder>
And inside the ContentPlaceHolder I got an Panel with a FileUpload. The thing is that the FileUpload doesn't find the file. Here I want to add RegisterAsyncPostBackControl to the Scriptmanager, but how do I do this when the panel is on another page?
The nested page code looks like this
<asp:Content ID="Content3" ContentPlaceHolderID="MasterIndhold_Member" runat="server">
<asp:panel runat="server" ID="Panel_MyProfile_Member" Visible="false">
<asp:FileUpload ID="File1" runat="server" />
<asp:LinkButton ID="LinkUploadImageMember" runat="server" onclick="LinkUploadImageMember_Click">Upload</asp:LinkButton>
And the CodeBehind for the FileUpload Looks like this
protected void LinkUploadImageMember_Click(object sender, EventArgs e)
{
if (File1.HasFile == true)
{
if ((File1.PostedFile.FileName.EndsWith(".jpg")) || (File1.PostedFile.FileName.EndsWith(".jpeg")) || (File1.PostedFile.FileName.EndsWith(".png")))
{
byte[] input = File1.FileBytes;
Bruger.UploadImage(input, int.Parse(Request.QueryString["ID"]));
}
}
}
Please keep code examples to C# and ASP.NET as I'm new to this stuff ^^
Thanks
You could also use the ScriptManagerProxy class if you need a ScriptManager on your content page, but I'm not sure whether you need this at all. Do you really need an UpdatePanel on every content page? (because you declared it on the master page). I think it might be better to declare the UpdatePanel within the content page.
Try to define a trigger for your linkbutton, otherwise HasFiles is always false
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:PostBackTrigger ControlID="LinkUploadImageMember" />
</Triggers>
<ContentTemplate>
<asp:FileUpload ID="File1" runat="server" />
<asp:LinkButton ID="LinkUploadImageMember" runat="server" Text=" upload " />
</ContentTemplate>
</asp:UpdatePanel>
If you cannot remove the UpdatePanel from the Masterpage, you could expose a property on the masterpage that gives access the updatepanel, like this:
public UpdatePanel MyUpdatePanel
{
get { return UpdatePanel1; }
}
From the contentpage you can access the update panel and update the triggers programmatically:
protected void Page_Load(object sender, EventArgs e)
{
((Site)Master).MyUpdatePanel.Triggers.Add(new PostBackTrigger() {
ControlID = LinkUploadImageMember.UniqueID });
}

updatepanel and javascript include file

I have found many solution for my issue but none doesn't work in my scenario.
I have created a test project to demo my concept.
Basically, there is a page that host a user control...
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
WebUserControl1 has a dropdownlist and two other webusercontrols (to be displayed based on the selection of dropdownlist element) inside updatepanel as below.
<%# Register Src="WebUserControl2.ascx" TagName="WebUserControl2" TagPrefix="uc2" %>
<%# Register Src="WebUserControl3.ascx" TagName="WebUserControl3" TagPrefix="uc3" %>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
</asp:DropDownList>
<asp:Panel ID="pnlCreditCard" Visible="false" runat="server">
<uc2:WebUserControl2 ID="WebUserControl21" runat="server" />
</asp:Panel>
<asp:Panel ID="pnlGiftCard" Visible="false" runat="server">
<uc3:WebUserControl3 ID="WebUserControl31" runat="server" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Code behind file for WebUserControl1 is .....
public enum PaymentMethod
{
CreditCard = 0,
GiftCard
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindPaymentMethods(Enum.GetValues(typeof(PaymentMethod)));
}
private void BindPaymentMethods(Array paymentMethods)
{
DropDownList1.DataSource = paymentMethods;
DropDownList1.DataBind();
if (paymentMethods.Length > 0)
{
DropDownList1.SelectedIndex = 0;
UpdateCreditOrGiftCardPanelVisibility();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateCreditOrGiftCardPanelVisibility();
}
private void UpdateCreditOrGiftCardPanelVisibility()
{
if(DropDownList1.SelectedValue == Enum.GetName(typeof(PaymentMethod),PaymentMethod.CreditCard))
{
pnlGiftCard.Visible = false;
pnlCreditCard.Visible = true;
}
else if (DropDownList1.SelectedValue == Enum.GetName(typeof(PaymentMethod), PaymentMethod.GiftCard))
{
pnlCreditCard.Visible = false;
pnlGiftCard.Visible = true;
}
}
Now, the problem starts here...There is an external javascript file [JScript1.js] (embedded resource) which basically is used to display an alert box.
<script language="javascript" type="text/javascript">
window.onload = function() {
alert('creditcard form');
}
WebUserControl2.ascx.cs code behind is
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptInclude(this.Page, this.Page.GetType().BaseType, "JScript1", Page.ClientScript.GetWebResourceUrl(this.Page.GetType().BaseType, "WebApplication1.JScript1.js"));
}
Alert window doesn't get displayed when I change the dropdownlist value. Even the script is getting registered three times (look in the firebug)
Need to use ScriptInclude instead of ScriptBlock as the original JS file is too big.
Can email the test app....
Thanks in Advance
After working around a bit, I found the solution.
I registered a ScriptManagerProxy in WebUserControl2.ascx
<asp:ScriptManagerProxy ID="ScriptManager1" runat="server" >
<Scripts>
<asp:ScriptReference Assembly="WebApplication1" Name="WebApplication1.JScript1.js" />
</Scripts>
</asp:ScriptManagerProxy>
Then on the code behind of the same control, added...
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ScriptManager.RegisterStartupScript(this, GetType(), "test", "doSomething();", true);
}
and the JScript1.js file looks like below.
function doSomething() {
alert('via dosomething control2 form');
}
Hope that helps. Though I had to litter around more in my practical scenario but this was certainly the way I got it working.
Thanks,

Categories