Pass Javascript Variable into ASP.NET CommandArgument - javascript

It doesn't look like this is possible, but is there any way to pass a javascript variable into the CommandArgument field? I'm trying to pass the facility_id variable so that the code behind can access the value.
Here is my aspx code:
<script type="text/javascript">
var facility_id = 50;
</script>
<asp:Button CssClass="btn btn-primary btn-lg" ID="submitBtn" runat="server" Text="Create EDD" CommandArgument='<% facility_id.Value %>' OnClick="submitBtn_Click" />

As you expect, the CommandArgument is a server-side property of Button server control and you can't assign it from client-side code because it does not render corresponding HTML attribute. However, you can set up a postback from client-side with __doPostBack() function as provided below:
<script>
var facility_id = 50;
$('#something').click(function () {
__doPostBack("<%= submitBtn.UniqueID %>", facility_id);
});
</script>
Code behind
protected void submitBtn_Click(object sender, EventArgs e)
{
// assumed 'facility_id' is an int? or Nullable<int> property,
// make sure the event argument is parseable to integer value
var evArg = int.Parse(Request.Form["__EVENTARGUMENT"]);
facility_id = evArg;
}
If you cannot use __doPostBack() function because it is undefined on the page, then you can handle PreRender event of that page and provide GetPostBackEventReference() method:
protected void Page_PreRender(object sender, EventArgs e)
{
ClientScript.GetPostBackEventReference(submitBtn, string.Empty);
}

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

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.

How to call a javascript method from aspx.cs

I want to call a method hello() in javascript from aspx.cs ( c# ) when a listbox1 item is selected.Using this code to do it but not working
protected void ListBox1_TextChanged(object sender, EventArgs e)
{
ClientManager.RegisterStartupScript(this, GetType(), "whatiskey","hello();", true);
}
function hello() {
alert("hiiiii");
var arr = ["<%=myvalue %>"];
}
Setting "AutoPostBack" property of ListBox to "true" and using Page.ClientScript.RegisterStartupScript(GetType(), "whatiskey", "hello();", true); worked for me
use
Response.Write("<script>hello();</script>");
EDIT
if all you wanna do is call a javascript on selection of an item, you can use onchange attribute as follows -
<asp:ListBox onchange="hello();" ID="ListBox1" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
</asp:ListBox>
<script>
function hello() {
alert("hello");
}
</script>

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

Label id is changing, how to fix this?

I have this asp:label in my page and what I want is to change the text from time to time. But label id is changing from page to page when i run the code. its been appended with "ctl00_bh_" something...
how to fix this?
here are my code snippets.
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "onLoad", "DisplaySessionTimeout()", true);
}
<asp:Label ID="lblSessionTime" runat="server" />
function DisplaySessionTimeout() {
document.getElementById("lblSessionTime").innerHTML = "updating text here";
sessionTimeout = sessionTimeout - 1;
if (sessionTimeout >= 0)
window.setTimeout("DisplaySessionTimeout()", 1000);
else
{
alert("Your current Session is over.");
}
}
thanks
In your Javascript you are trying to access the server side control, you need to use the ClientID, try
document.getElementById("<%= lblSessionTime.ClientID%>").innerHTML ="updating text here";
Or ClientIDMode in aspx page if you are using .Net framework 4 or higher
<asp:Label ID="lblSessionTime" runat="server" ClientIDMode="Static" />

Categories

Resources