get element in javascript - javascript

I have a Repeater which i am bounding some data to it. Now my problem is how i can refer to the data I have in my label in the repeater from the javascript. My code is the following;
CODEBEHIND
protected void Page_Load(object sender, EventArgs e)
{
// bool boolfound = false;
string connstring = String.Format("Server=localhost; Port=5432; User Id=postgres; Password=database; Database=valletta;");
using (NpgsqlConnection conn = new NpgsqlConnection(connstring))
{
try
{
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("select get_points('temp_intersect', 'point','id',17339)", conn);
NpgsqlDataReader dr = cmd.ExecuteReader();
currentpoint.DataSource = dr;
currentpoint.DataBind();
}
catch (Exception)
{
ClientScript.RegisterStartupScript(this.GetType(), "", "$(document).ready(function(){alert('problem with connection')});", true);
}
}
}
ASP
<asp:Repeater ID="currentpoint" runat="server">
<ItemTemplate>
<div>
<asp:Label ID="hiddenlabel" runat="server" Text='<%# Eval("get_points")%>' Visible="false">
</asp:Label>
</div>
</ItemTemplate>
</asp:Repeater>

You can change the ClientIDMode to Predictable or static, works well with javascript.
Read this post

Try this one:
document.getElementById('<%=currentpoint.FindControl("hiddenlabel").ClientID%>')

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

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

open NavigateUrl window through template field

I try to open NavigateUrl Telerik Window from a button in a grid view which exist in an update panel but i fail , it doesn't open the window at all
My .aspx :
<asp:TemplateField HeaderText="details" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="ibtn_details" runat="server" ImageUrl="~/images/details.png"
CommandArgument='<%#((GridViewRow)Container).RowIndex%>' CommandName="Get_details" />
</ItemTemplate>
</asp:TemplateField>
<telerik:RadWindow runat="server" ID="radwin_popupdetails" NavigateUrl="PopUpDetail.aspx"
Modal="true" InitialBehaviors="Maximize">
</telerik:RadWindow>
<script type="text/javascript">
function openWinNavigateUrl() {
$find("<%=radwin_popupdetails.ClientID %>").show();
}
</script>
My .cs :
protected void gv_inbox_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Get_details")
{
Session["main_code"] = int.Parse(((HiddenField)gv_inbox.Rows[index].Cells[1].FindControl("HDN_MainCode")).Value);
//System.Web.UI.ScriptManager.RegisterClientScriptBlock(UpdatePanel2, UpdatePanel2.GetType(), "Open window", "openWinNavigateUrl(); return false;", true);
RadScriptManager.RegisterStartupScript(this, this.GetType(), "tabSelectedScript", "openWinNavigateUrl();", true);
}
}
Take a look at the following resources, they will help you either do it this way, or even improve:
http://www.telerik.com/community/forums/aspnet-ajax/window/opening-radwindow-from-the-server.aspx
http://demos.telerik.com/aspnet-ajax/controls/examples/integration/gridandwindow/defaultcs.aspx?product=window

Cannot get document.GetElementById working right

I am trying to call a javascript function from onClick event of an asp server button. I have this button and a label in an update panel.
In aspx:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="Button1" runat="server"
style="z-index: 1; left: 49px; top: 119px; position: absolute; height: 26px;" Text="Button"
onclick="Button1_Click"/>
<asp:Label ID="Label1" runat="server" Text="l1"
style="position:absolute; top: 123px; left: 127px;"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, typeof(Button), "me", "me()", true);
}
Javascript in aspx:
<script type="text/javascript">
function me()
{
document.getElementById('<%= Label1.ClientID %>').value="clicked";
}
</script>
All I am trying to do is on button click the label's value should be changed to 'clicked', which isn't happening and no error as well in firebug. Where am I wrong in the me( )?
P.S: I am doing this to learn calling a javascript function from code behind. So any optimizations to the code are also welcome. (I actually have much lot of code to implement in the JS function later so appropriate suggestions please)
As far as I remember the Label control is rendered as a <div> or <span> (can't remember exactly), not a text input field. So you should be setting its innerHTML property not the value:
document.getElementById('<%= Label1.ClientID %>').innerHTML = 'clicked';
or simply do it on the server side instead of registering clientside callbacks:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "clicked";
}
UPDATE:
As requested in the comments section here's how you could pass parameters to the clientside callback from the server:
protected void Button1_Click(object sender, EventArgs e)
{
string param1 = ...
double param2 = ...
int param3 = ...
var serializer = new JavaScriptSerializer();
ScriptManager.RegisterClientScriptBlock(
this,
typeof(Button),
"me",
string.Format("me({0})", serializer.Serialize(new { param1 = param1, param2 = param2, param3 = param3 })),
true
);
}
and your callback:
function me(values) {
// you could use values.param1, values.param2, values.param3, ... here
}

Categories

Resources