Label id is changing, how to fix this? - javascript

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" />

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

Pass Javascript Variable into ASP.NET CommandArgument

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

How to call Javascript function from server side asp.net

I have a Textbox in GridView I want to change the Label.Text if the text in Textbox is changed. But I am not able call javascript function written in .cs page. Is there any mistake in TbUnitCost_TextChanged method.
This is my aspx page
<ItemTemplate>
<asp:TextBox Style="text-align: right" ID="TbUnitCost" runat="server" Width="80px" Text='<%#Bind("Unit_Cost")%>' AutoPostBack="true" OnTextChanged="TbUnitCost_TextChanged" TextMode="Number"></asp:TextBox>
</ItemTemplate>
Code behind Page is as follows
protected void TbUnitCost_TextChanged (object sender, EventArgs e)
{
GridViewRow currentRow = (GridViewRow)((TextBox)sender).Parent.Parent;
int rowNo = currentRow.RowIndex;
string gridName = "GridWorkExpenses";
TextBox tbunitCost = (TextBox)currentRow.FindControl("TbUnitCost");
int row = Convert.ToInt32(tbunitCost.Text);
tbunitCost.Attributes.Add("onchange","javascript:calculateTotalCost('"+rowNo+"','"+gridName+"');");
}
and javascript Function is:
<script type ="text/javascript">
function calculateTotalCost(rowNo, GridName) {
if (GridName== 'GridWorkExpenses') {
var rowscount = document.getElementById('<%=GridWorkExpensesSheet.ClientID%>').rows.length;
return calculateTotalUnitCost("GridWorkExpensesSheet", rowscount,rowNo);
}
}
</script>
Try using this:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "CalculateTotalCost", true);
Describe any further problem (if there is any).
ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", "<script type='text/javascript'>CalculateTotalCost</script>", false);
is another method
This is a very old discussion [1]:Difference between RegisterStartupScript and RegisterClientScriptBlock?
Please refer this too.
hi you must write all of command in the one string
ScriptManager.RegisterClientScriptBlock((sender as Control), GetType(), "jQueryCommand", "$('.MenuLoginLink').hide();$('.MenuUsername').show();$('.MenuUsername').text('" + Currentmember.Mobile + "');$('.MenuExit').show();" +
" $('.btnLoginInFriends').hide();$('#HiddenSession').val('" + int.Parse(Session["CurrentUserID"].ToString()) + "');", true);

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

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