JavaScript setInterval function not updating Gridviews in <div> elements - javascript

I have 2 items where the label I use (for testing at least) refreshes with the last update time. However, the GridViews inside the elements only update once. The data parsed out and wrote out normally in a console app, so I'm not sure what the hiccup is. The strange part, is that although it does load data for the first iteration, but doesn't refresh for new data.
Is it the setInterval function that's not working? I've tried that, and a recursive setTimeout function that I found, but neither worked. Both have been included with comments showing attempt 1 and 2.
EDIT Attempt 2 works if i do just an alert(), but calling the C# method makes it run only once.
Any help would be greatly appreciated.
Here's the page:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<link href="CSS/Stylesheet.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function ProcessData() //Attempt 1
{
<%Process_Data();%>
setTimeout(ProcessData, 3000);
}
setInterval(function () {
ProcessData()
}, 3000);
</script>
<script type="text/javascript"> // Attempt 2
function ProcessData()
{
<%Process_Data();%>
setTimeout(ProcessData(), 5000);
}
ProcessData();
</script>
<div class="Images">
<asp:Label ID="Label1" runat="server" Text="123"></asp:Label><br />
<asp:Label ID="Label2" runat="server" Text="123"></asp:Label><br />
</div>
<div id="dnrLeft" class="DonorsLeft">
<div class="col-md-4">
<asp:GridView ID="dnrResultsLeft" runat="server" HorizontalAlign="Left" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="DonorName" HeaderText="" />
<asp:BoundField DataField="Club" HeaderText="" />
</Columns>
</asp:GridView>
</div>
</div>
<div id="dnrRight" class="DonorsRight">
<div class="col-md-4">
<asp:GridView ID="dnrResultsRight" runat="server" HorizontalAlign="Right" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="DonorName" HeaderText="" />
<asp:BoundField DataField="Club" HeaderText="" />
</Columns>
</asp:GridView>
</div>
</div>
</asp:Content>
And here's the code behind it:
namespace DnrBoards
{
public partial class DonorBoardOsh : System.Web.UI.Page
{
List<Donors> dnrs = new List<Donors>();
protected void Page_Load(object sender, EventArgs e)
{
using (DnrBrdDataContext DR = new DnrBrdDataContext())
{
var dnrList = (from d in DR.DonorBoards
where (d.SiteLocation == "OSH") && (d.Club != "0 Donations")
orderby d.Donation_Type, d.Donation_Sum, d.Donor ascending
select new
{
_DonorName = d.Donor.ToString(),
_Club = d.Club
}).ToList();
foreach (var item in dnrList)
{
dnrs.Add(new Donors(item._DonorName, item._Club));
}
}
Label2.Text = "Last data pull at: " + DateTime.Now.ToString();
}
protected void Process_Data()
{
List<Donors> dlLeft = new List<Donors>();
List<Donors> dlRight = new List<Donors>();
for (int i = 0; i < 43; i++)
{
try
{
dlLeft.Add(dnrs[0]);
dnrs.RemoveAt(0);
}
catch { }
}
for (int i = 0; i < 43; i++)
{
try
{
dlRight.Add(dnrs[0]);
dnrs.RemoveAt(0);
}
catch { }
}
dnrResultsLeft.GridLines = GridLines.None;
dnrResultsLeft.DataSource = dlLeft;
dnrResultsLeft.DataBind();
dnrResultsRight.GridLines = GridLines.None;
dnrResultsRight.DataSource = dlRight;
dnrResultsRight.DataBind();
dlLeft.Clear();
dlRight.Clear();
Label1.Text = "Last Refresh: " + DateTime.Now.ToString();
}
}
}

Page_Load will run with every callback update, so dnrs will always be updated with new data from the database on every tick, even if you remove it in the previous one.
The RemoveAt(i) logic is strange. RemoveAt() removes an item from the list at the position specified, but you're increasing the position each iteration. Simultaneously the array is getting smaller each iteration (because you're removing an item), so will start failing when you get halfway through the list. If you're meaning to take the first item each time from the list, you should add( dnrs[0]) and RemoveAt(0). This will add the first item from the list, then remove it from dnrs, meaning at the next iteration the next item will now be at index 0.

Related

Set and get session variable on callback

I am using Devexpress controls in asp.net c#.
I have a GridView with a CustomButtonColumn. When I click on that button it performs a callback and gets the row key. There I set a Session variable with the row key.
On Page2 I want to use that Session to bind a parameter in a XtraReport.
[C#]
Page1
<script type="text/javascript">
function OnClick(s, e) {
if (e.buttonID == "SF") {
//Session["parameter_id"] = e.visibleIndex;
// gridAdmin.GetRowValues(gridAdmin.GetFocusedRowIndex(), 'ID', OnGetRowValues);
sf.PerformCallback(e.visibleIndex);
window.location = "PrintView.aspx";
}
}
</script>
<dx:ASPxPopupControl ID="ASPxPopupControl3" runat="server" CloseAction="CloseButton" ClientInstanceName="pcSF"
AllowDragging="True" PopupAnimationType="None" Modal="True" PopupHorizontalAlign="WindowCenter" PopupVerticalAlign="WindowCenter"
CssClass="panel1" Style="font-size: 20px" CloseOnEscape="true" HeaderText="SF">
<HeaderStyle BackColor="#FF8000" Font-Bold="True" HorizontalAlign="Center" />
<ContentCollection>
<dx:PopupControlContentControl>
<dx:ASPxCallbackPanel ID="pnlSF" runat="server" BackColor="White" ClientInstanceName="sf" OnCallback="pnlSF_Callback" >
<PanelCollection>
<dx:PanelContent>
</dx:PanelContent>
</PanelCollection>
</dx:ASPxCallbackPanel>
</dx:PopupControlContentControl>
</ContentCollection>
</dx:ASPxPopupControl>
protected void pnlSF_Callback(object sender, CallbackEventArgsBase e)
{
Session["parameter_id"] = GridViewAdmin.GetRowValues(Convert.ToInt32(e.Parameter), "ID").ToString();
// Response.Redirect("PrintView.aspx");
}
Page 2
protected void Page_Load(object sender, EventArgs e)
{
XtraReport1 repTest = new XtraReport1();
repTest.RequestParameters = false;
repTest.parameter1.Value = Session["parameter_id"];
repTest.parameter1.Visible = false;
repTest.CreateDocument();
this.ASPxDocumentViewer1.Report = repTest;
this.ASPxDocumentViewer1.DataBind();
}
When I click on that custom button from gridview and loads page2 it appears this error.
Why?
I saw that on debug when that error appears the callback is not done. It does not enter in pnlSF_Callback() function.

Assign value of textbox in Javascript and set the value in session with C#

I've been struggling for a while with a Javascript/C# issue i have. I've been trying to set a Session variable from Javascript. I tried to use page methods before but it resulted in my javascript crashing.
In the javascript :
PageMethods.SetSession(id_Txt, onSuccess);
And this page method :
[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
Page aPage = new Page();
aPage.Session["id"] = value;
return value;
}
I haven't had any success with this. Therefore, i tried to set the value of a textbox from my javascript and put a OnTextChanged event in my c# to set the session variable but the event is not fired.
In the javascript:
document.getElementById('spanID').value = id_Txt;
In the html :
<asp:TextBox type="text" id="spanID" AutoPostBack="true" runat="server"
ClientIDMode="Static" OnTextChanged="spanID_TextChanged"
style="visibility:hidden;"></asp:TextBox>
In the cs :
protected void spanID_TextChanged(object sender, EventArgs e)
{
int projectID = Int32.Parse(dropdownProjects.SelectedValue);
Session["id"] = projetID;
}
Does anyone have an idea as of why none of my events where fired ? Do you have an alternative solution that I could try ?
I found the issue, I didn't have the enableSession = true and i had to use the HttpContext.Current.Session["id"] = value, like stated by mshsayem. Now my event is fired properly and the session variable is set.
First, ensure you have sessionState enabled (web.config):
<sessionState mode="InProc" timeout="10"/>
Second, ensure you have page-methods enabled:
<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
Third, set session value like this (as the method is a static one):
HttpContext.Current.Session["my_sessionValue"] = value;
Sample aspx:
<head>
<script type="text/javascript">
function setSessionValue() {
PageMethods.SetSession("boss");
}
</script>
</head>
<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
<asp:Button ID="btnSetSession" Text="Set Session Value (js)" runat="server" OnClientClick="setSessionValue();" />
<asp:Button ID="btnGetSession" Text="Get Session Value" runat="server" OnClick="ShowSessionValue" />
<br/>
<asp:Label ID="lblSessionText" runat="server" />
Sample code behind:
[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
HttpContext.Current.Session["my_sessionValue"] = value;
return value;
}
protected void ShowSessionValue(object sender, EventArgs e)
{
lblSessionText.Text = Session["my_sessionValue"] as string;
}

invoke method batcheditcommand from C#.net [duplicate]

This question already has an answer here:
how to use webmethod with telerik batch edit grid
(1 answer)
Closed 7 years ago.
I used telerik:RadGrid batch editing; to fill this grid I used below syntax:
function GridBind(GridID, GridData) {
var TableView = GridID.get_masterTableView();
TableView.set_dataSource(GridData); TableView.dataBind();
}
To Invoke batcheditcommand I used below syntax. It’s written under non-postback button Javascript event:
function SaveAllChanges(sender,args) {
var batchManager = $find('<%=RadGrid1.ClientID%>').get_batchEditingManager();
var tableViews = [];
tableViews.push($find('<%=RadGrid1.ClientID%>').get_masterTableView());
batchManager.saveTableChanges(tableViews);
}
But unfortunately it did not fire server event RadGrid1_BatchEditCommand, so I want to invoke Radgrid batcheditcommand from code behind in C#.net.
A quick POC that worked for me:
markup:
<telerik:RadGrid ID="RadGrid1" runat="server" OnBatchEditCommand="RadGrid1_BatchEditCommand">
<MasterTableView EditMode="Batch">
<Columns>
<telerik:GridBoundColumn DataField="first"></telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="second"></telerik:GridBoundColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:Button ID="Button1" Text="bind grid" OnClientClick="bindTheGrid(); return false;" runat="server" />
<asp:Button ID="Button2" Text="save grid" OnClientClick="SaveAllChanges(); return false;" runat="server" />
<script>
function bindTheGrid() {
var grid = $find("<%=RadGrid1.ClientID%>");
var data = [{ first: 1, second: 1 }, { first: 2, second: 2 }];
GridBind(grid, data);
}
function GridBind(GridID, GridData) {
var TableView = GridID.get_masterTableView();
TableView.set_dataSource(GridData);
TableView.dataBind();
}
function SaveAllChanges(sender, args) {
var batchManager = $find('<%=RadGrid1.ClientID%>').get_batchEditingManager();
var tableViews = [];
tableViews.push($find('<%=RadGrid1.ClientID%>').get_masterTableView());
batchManager.saveTableChanges(tableViews);
}
</script>
and server code
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
RadGrid1.DataSource="";
RadGrid1.DataBind();
}
}
protected void RadGrid1_BatchEditCommand(object sender, GridBatchEditingEventArgs e)
{
Response.Write(DateTime.Now.ToString());
}
where you would need to work a bit on the client-side binding.
Make sure you have no script errors.
In the first function, do you pass a grid object or an ID in the GridID object? If only and ID, use $find() first to get a reference.

passing clientID to javascript and extracting a value, clarification

Forgive the noob question, but I'm trying to get my head wrapped around this. I have some controls that are inside of an in a listview that are used to submit some information. I'm running a test pattern here to do this, but I'm getting object undefined errors. All of the articles I've seen about this are kind of vague. In this example, I'm trying to pass the id of a textbox, then pull the value from that in javascript. Can you tell me what I'm doing wrong?
<form id="form1" runat="server">
<asp:ScriptManager runat="server" />
<script type="text/javascript">
function ClientIDS(id) {
var info = document.getElementById(id).value;
alert(info);
return false;
}
</script>
<asp:ListView runat="server" ID="lsvTest">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtTextBox" />
<asp:Button runat="server" ID="btnSubmit" Text='<%#Eval("Name") %>' OnClientClick="ClientIDS('<%=txtTextBox.ClientID %>')" />
</ItemTemplate>
</asp:ListView>
</form>
Thanks
if you are want to doing using jquery than try this
just replace in button onclientclick with this one
OnClientClick="ClientIDS(this);"
and than find your previous input text in to asp:listview
function ClientIDS(obj) {
var txt = $(obj).prevAll('input[id*="txtTextBox"]:first');
alert($(txt).val());
return false;
}
You can't have inline code in a property for a server control.
Generally I would do this in the codefile.
for (int j = 0; j < this.lsvTest.Items.Count; j++)
{
var btnSubmit = (Button)this.lsvTest.Items[j].FindControl("btnSubmit");
var txtTextBox = (TextBox)this.lsvTest.Items[j].FindControl("txtTextBox");
btnSubmit.Attributes["onclick"] = string.Format("ClientIDS('{0}')", txtTextBox.ClientID);
}
Java Script Code
<script type="text/javascript">
function ClientIDS(Btnid) {
var textBoxID = Btnid.id.replace('btnSubmit', 'txtTextBox');
var info = document.getElementById(textBoxID).value;
alert(info);
return false;
}
</script>
HTML Code
<asp:ListView runat="server" ID="lsvTest">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtTextBox" />
<asp:Button runat="server" ID="btnSubmit" Text='<%#Eval("Name") %>' OnClientClick="ClientIDS(this)" />
</ItemTemplate>
</asp:ListView>
first of all, you're using javascript to do what you're jQuery library should be doing.
For example:
var info = document.getElementById(id).value;
// is easier as
var info = $("#"+id).val();
Secondly, it's been awhile, but i dont think you can put your asp script text in the form like that
You can use ItemDataBound event for the repeater to make this. See the following code
protected void lsvTest_ItemDataBound(object sender, ListViewItemEventArgs e)
{
string txtbox = e.Item.FindControl("txtTextBox").ClientID;
Button btn = e.Item.FindControl("btnSubmit") as Button;
btn.OnClientClick = string.Format("ClientIDS('{0}')", txtbox);
}

How can I recall a javascript function after updatepanel update

<asp:UpdatePanel ID="UpdatePanel2" runat="server"
OnLoad="UpdatePanel2_Load" UpdateMode="Conditional">
<ContentTemplate>
<script type="text/javascript">
myFunction();
</script>
<asp:Label ID="Label1" runat="server" Text="1" Width="18px"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
C#:
if(condition)
{
UpdatePanel2.Update();
}
protected void UpdatePanel2_Load(object sender, EventArgs e)
{
Label1.Text += 1;
}
the Label1's value is changing but it doesn't call myFunction(). I want to call it one more time after the some condition but not using setTimeout to auto call, some ideas?
When the UpdatePanel updates the DOM and rewrites script blocks into the DOM, they are not re-executed. You need to get on the client-side event that fires after the UpdatePanel is finished and re-execute your JS blocks:
<script type="text/javascript">
function handleEndRequest(sender, args)
{
var panel = document.getElementById(sender._postBackSettings.panelID);
var scripts = panel.getElementsByTagName('script');
for(var i=0;i<scripts.length;i++) {
eval(scripts[i].innerHTML);
}
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(handleEndRequest);
</script>
I have made it works by refreshing the whole page

Categories

Resources