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.
Related
I am using ASP.NET UpdatePanel for partial postback. Somehow after the server side postback (ddl_SelectedIndexChanged), the value set by a Javascript function (lblTotal's value of 100) gets removed. Is there anyway to preserve value set by the Javascript function?
JavaScript:
<script type="text/javascript">
function calculateTotal() {
var lblTotal = document.getElementById("<%= lblTotal.ClientID%>");
lblTotal.innerHTML = "100";
}
</script>
HTML:
<asp:UpdatePanel ID="UpdateGrid" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddl" runat="server" OnTextChanged="ddl_SelectedIndexChanged" AutoPostBack="true" />
<asp:CheckBox ID="chkLevels" runat="server" onclick="calculateTotal()" />
<asp:Label ID="lblTotal" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
C# / Code Behind:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
// Some code
}
The problem is here is that when you change data with calculateTotal in Javascript, server does not know about changes since you don't post back data to server.
So you need to trigger the postback event with __doPostBack():
Client side:
function calculateTotal() {
var lblTotal = document.getElementById("<%= lblTotal.ClientID%>");
//Calculation
var totalValue = "100";
__doPostBack('chkLevels', totalValue);
}
Page_Load on Server side :
protected void Page_Load(object sender, EventArgs e)
{
if (Request["__EVENTTARGET"] == "chkLevels")
{
var totalValue = Request["__EVENTARGUMENT"];
lblTotal.Text = totalValue;
}
}
See: how to use __doPostBack function in asp.net
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.
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.
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;
}
I want to add a client-side JavaScript event handler that will fire each time a row is selected or deselected on an ASP.NET Telerik RadGrid and I need to add it from JavaScript without server-side code. How can I accomplish this?
You can achieve this by using RadAjaxManager.
ASPX:
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server"
onajaxrequest="RadAjaxManager1_AjaxRequest"></telerik:RadAjaxManager>
JS:
<script type="text/javascript">
function onclientrowclick(sender, args) {
$find("<%= RadAjaxManager1.ClientID %>").ajaxRequest();
}
</script>
C#:
protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
//your code
}
EDIT:
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="true" AllowMultiRowSelection="true" >
<ClientSettings Selecting-AllowRowSelect="true">
<ClientEvents OnRowSelecting="OnRowSelecting" OnRowDeselecting="OnRowDeselecting" />
</ClientSettings>
</telerik:RadGrid>
JS:
function OnRowDeselecting(sender, args) {
alert("deselect");
}
function OnRowSelecting(sender, args) {
alert("select");
}