Set and get session variable on callback - javascript

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.

Related

UpdatePanel postback removes changes made using javascript

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

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.

session cookie asp.net c#

please need help . actully i want to pass the info from page 1 to 2 using cookie but every i click buttom add to set a new cookie ....no just set the same nae and modify value . and read all cookie as list i dont know if u will understaidn what i want !!
here my code
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie Cookie = new HttpCookie("result");
Cookie["text1"] = TextBox1.Text;
Cookie["text2"] = TextBox2.Text;
Cookie.Expires = DateTime.Now.AddDays(2);
Response.Cookies.Add(Cookie);
Response.Redirect("WebForm2.aspx");
}
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie Cookie = Request.Cookies["result"];
if (Cookie != null)
{
Ldonate.Text = Cookie["text1"] ;
Litem.Text = Cookie["text2"] ;
}
Ldonate.Text = Request.Cookies["result"]["text1"];
Litem.Text = Request.Cookies["result"]["text2"];
this is how you can access to cookies

JavaScript display property

In my form I have a textbox and a calendar along with other controls:
<asp:TextBox ID="TextBox2" runat="server" onfocus="CalOpen()" asp:TextBox>
<asp:Calendar ID="Calendar1" runat="server" style="display:none;"
onselectionchanged="Calendar1_SelectionChanged"></asp:Calendar>
<script type="text/javascript">
function CalOpen()
{
var cal = document.getElementById('<%=Calendar1.ClientID%>');
cal.style.display='block';
}
</script>
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox2.Text = Calendar1.SelectedDate.ToLongDateString();
Calendar1.Visible = false;
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Calendar1.Visible = true;
}
For the first time it worked fine,
but, second time when I click TextBox2, that is, after selecting date for the first time the
browser is throwing error "object required".
I am unable to know where I went wrong.
Please help me in making my code correct.
When you write Calendar1.Visible = false; in server-side code, it doesn't render the calendar at all. Therefore, there is no calendar element for the Javascript to show.
Instead, you should make a CSS class that applies display: none to the calendar, and set the CssClass property to that class on the server.
For example:
<style type="text/css">
.Hidden {
display: none;
}
</style>
<asp:Calendar ID="Calendar1" runat="server" CssClass="Hidden"
onselectionchanged="Calendar1_SelectionChanged"></asp:Calendar>
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox2.Text = Calendar1.SelectedDate.ToLongDateString();
Calendar1.CssClass = "Hidden";
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Calendar1.CssClass = "";
}

Categories

Resources