Ajax update panel causes blank space - c#

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();
}

Related

dropdown onselectedindexchanged event not firing and value kept on postback c#

I can't get the dropdown onselectedindexchanged event to fire, and when I make a selection it resets the value of the dropdown onpostback, even though I have the if (!ispostback) in the page load event.
this is a content page in a master page in asp in case that matters.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:DropDownList ID="EventSVCProgList" runat="server"
EnableViewState="true"
OnSelectedIndexChanged="EventSVCProgList_SelectedIndexChanged"
AutoPostBack="true"></asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection constr = new SqlConnection(ConfigurationManager.ConnectionStrings["CBTestDBConnectionString"].ConnectionString);
SqlCommand eventsvcprogCMD = new SqlCommand("select*from SvcProg where eventatteligable=1", constr); // table name
SqlDataAdapter eventsvcadapt = new SqlDataAdapter(eventsvcprogCMD);
DataSet eventsvcset = new DataSet();
constr.Open();
eventsvcadapt.Fill(eventsvcset); // fill dataset
EventSVCProgList.DataTextField = eventsvcset.Tables[0].Columns["SvcProgID"].ToString(); // text field name of table dispalyed in dropdown
EventSVCProgList.DataValueField = eventsvcset.Tables[0].Columns["eventatteligable"].ToString();
EventSVCProgList.DataSource = eventsvcset.Tables[0]; //assigning datasource to the dropdownlist
EventSVCProgList.DataBind(); //binding dropdownlist
constr.Close();
}
}
protected void EventSVCProgList_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Eat Poop");
var somevalue = EventSVCProgList.SelectedValue;
}
There are couple of things.
1) You need to add a Script Manager to the page at the top if not added already(it will give you a runtime error if you have not added a script Manager to the page)
2) You need to change the Update Panel content as shown below
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="EventSVCProgList" runat="server" AutoPostBack="True" OnSelectedIndexChanged="EventSVCProgList_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="EventSVCProgList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
There seems that any parent control or page leven ViewState is disabled. please check in debug mode that what value you getting for EventSVCProgList.EnableViewState and other parent controls' as well.
thanks for the help. its still not working so i'm just going to try to use javascript instead. its got to be some fundamental flaw with the way the master page or content page is setup.

Why my Drop down list is not getting binded upon button click?

i am trying to rebind my Dropdown upon button click, in particular if Block but it doesn't rebind, i mean that it should reload the drop down, kinda refresh and first item should be selected, i am doing this but not getting rebinded
Code:(It si inside buttong click event)
if (NotAssignedConductors.Length > 0)
{
string[] NotAssignedConductorsArray = NotAssignedConductors.Split(':');
foreach (string str in NotAssignedConductorsArray)
{
ResultLabel.ResultLabelAttributes(str, ProjectUserControls.Enums.ResultLabel_Color.Red);
}
FillDropDownListDevices();
}
Method being called:
public void FillDropDownListDevices()
{
DropDownListDevices.DataSource = ManageTransport.ManageConductorDevices.GetDevices();
DropDownListDevices.DataTextField = "TerminalSNO";
DropDownListDevices.DataValueField = "DeviceID";
DropDownListDevices.DataBind();
DropDownListDevices.Items.Insert(0, new ListItem("None", "-1"));
}
Button:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownListDevices" AutoPostBack="true" runat="server" OnSelectedIndexChanged="DropDownListDevices_SelectedIndexChanged" CssClass="form-control">
</asp:DropDownList>
<ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnCreate" EventName="click" />
</Triggers>
</asp:updatePanel>
There are many possibilities
If you are using update panel make sure you trigger update-panel to update on button click
check your page_load/page_loadComplete event and make sure you are not binding drop-down again .
check your browser console it throws any error on button click?
Create Post back trigger on update panel
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownListDevices" AutoPostBack="true" runat="server" OnSelectedIndexChanged="DropDownListDevices_SelectedIndexChanged" CssClass="form-control">
</asp:DropDownList>
<ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:updatePanel>
Put your first time binding method on Postback
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//means no postback..page loaded first time
// Put your first time Binding method here
}
}

Unable to Update label Outside Update Panel

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.

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];

Update panel from a server side thread

I am trying to develop a chat using aspx. I already got it working with asmx + winform but now I have problems with asmx + aspx.
Basically what I want to do is call the WebMethod CheckForMessages every two seconds and, if there are messages, add them to a list box inside an update panel and do UpdatePanel1.Update();.
The problem is that apparently I can' t do this using a thread like I do in my winform.
void check() {
while (true) {
Thread.Sleep(2000);
string message = CheckForMessages();
if (message != "") {
ListBox1.Items.Add(message);
UpdatePanel1.Update();
}
}
}
I start the thread like this:
protected void Page_Load(object sender, EventArgs e) {
timer = new Thread(new ThreadStart(check));
timer.Start();
}
It doesn't throw an exception or anything, the program runs as intended. The web service is called, a string is returned if there is a message, the thread adds the message to the list and calls UpdatePanel1.Update();. Yet the panel is not updated.
What could the problem be ?
In ASP.Net you can use timer control along with updatepanel.
<asp:UpdatePanel runat="server" ID="uxUpdatePanel" UpdateMode="Conditional" EnableViewState="true">
<ContentTemplate>
<div>
<asp:Label ID="Label1" runat="server" style="display:none;"><%=GetMessageLog()%></asp:Label>
<asp:ListBox runat="server" ID="ListBox1" EnableViewState="true">
</asp:ListBox>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="uxTimer" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:Timer runat="server" ID="uxTimer" Interval="2000">
</asp:Timer>
And in Code-behind you to code like:
public string GetMessageLog()
{
string message = CheckForMessages();
if (message != "") {
ListBox1.Items.Add(message);
return DateTime.Now.ToLongTimeString();
}
This should work for you. But I will recommend you to use Javascript and JQuery to call Web-Service asynchronously with setTimeout function.
Instead of the server actively pushing changes to the client, try the opposite : make the client actively query the server, and update its state accordingly.
One way to do that is create a button to query the server manually. After you verify that it works, make the button hidden using css, and set a function to click the button in a regular interval. You can use javascript setInterval for this.
To click a button in javascript, you can do something like this :
setInterval(function(){ document.getElmtById(“<%= theButton.ClientID %>").click(); }, 2000);
The above code should click theButton every 2 seconds.
You should have a look at SignalR.net. Jabbr.net is based on signalR and exactly what you need. https://github.com/davidfowl/JabbR
yes Vishal... maybe less complex:
<asp:UpdatePanel ID="updatePanelPromptB" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="labelPlayback" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timerPromptB" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:Timer runat="server" ID="timerPromptB" OnTick="timerPromptB_Tick" Enabled="false" Interval="4000" />
private void promptBottom(string text)
{
labelPlayback.Text = text;
updatePanelPromptB.Update();
timerPromptB.Enabled = true;
}
protected void timerPromptB_Tick(object sender, EventArgs e)
{
labelPlayback.Text = "OK";
timerPromptB.Enabled = false;
}

Categories