Call A Java Script Function From C# Code Behind - javascript

I am attempting to populate a html page by passing in values using QueryString and my values are passing in the QueryString but my limited to NO knowledge of JS is preventing me from being able to deduce why the textbox on the page isn't populating with the passed value.
This is my HTML showing the JS Function
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Test.aspx.cs" Inherits="TestProject.Pages.Test" %>
<asp:Content ID="ContentHeaderID" ContentPlaceHolderID="MainContent" runat="Server">
<div class="BackgroundOfWhite">
<font class="BB">Select Instructor:</font>
<asp:DropDownList runat="server" ID="dropdown1"
AutoPostBack="true" CssClass="DropDownLists" ></asp:DropDownList>
<asp:Button runat="server" ID="btnOpenPage"
CssClass="Buttons" Text="Open Page With Params" OnClick="btnLoadPage_Click" />
<div class="White"></div>
</div>
<script type="text/javascript">
document.getElementById('InstructorName').value = Instructor;
</script>
This is my C# info here
protected void btnLoadPage_Click(object sender, EventArgs e)
{
string openthis = "http://whiskeyinthewatertestofsendingdata.html";
string Instructor = "Tyler Moore";
Response.Redirect(openthis+"?"+Instructor);
}
I feel that the issue is I am not actually calling the JS function to populate the textbox on the hmtl page, but how would I do such?
EDIT:
This is the html behind the textbox
<input id="InstructorName" name="InstructorName" maxlength="255" style="width: 240px;">
EDIT 2
I see this 1st few lines of HTML of the page...does this mean on the page load they force the fields to have a null value (which of course would mean their is no way to achieve what I am after)
<head>
<script type="text/javascript">
var forcefieldstonull =
{
"InstructorName":null,
"InstructorClass":null,
"InstructorBuilding":null,
"InstructorRoomNum":null
};

Try this:
protected void btnLoadPage_Click(object sender, EventArgs e)
{
string openthis = "http://whiskeyinthewatertestofsendingdata.html";
string Instructor = "Tyler Moore";
Response.Redirect(openthis+"?Instructor="+Instructor);
}
and then, on your page, change your javascript function to do it like this:
<script type="text/javascript">
document.getElementById('InstructorName').value = '<%=Request.QueryString["Instructor"]%>';
</script>

You have to wait for the page to be loaded completely before you can change it's elements.
Though the javascript is at the bottom it comes to my mind that it might be executed before the InstructorName div is rendered.
You should surround it with window.onload() to make sure that it is executed after the page is fully loaded. https://developer.mozilla.org/de/docs/Web/API/GlobalEventHandlers/onload
Additionally what you can do is simply check the Browsers console if the script gives you an error.

Related

Call code from code behind on page load in ASP.net?

I am simly trying to call the code from a code behind immediateky, as soon as the page loads.
How can I accomplish this? I tried making an invisible button and then tried clicking that on load, but that is not working for me. Hoping there is a simpler way.
This is the code behind. Filename is CodeBehind.aspx.cs:
public partial class DoTheThing: InjectablePageBase
{
private string GetURL(Object sender, EventArgs e){
// RUN MY CODE
}
}
And this is the relevant part of the .aspx file:
<%# Page Language="C#" AutoEventWireup="false" CodeBehind="CodeBehind.aspx.cs" Inherits="Test.GuideMe.DoTheThing" MasterPageFile="~/Theme/Framework.Master"%>
<asp:Content ID="Content2" runat="server" ContentPlaceHolderID="PageContentPlaceHolder">
<script Language="JavaScript">
window.onload = function() { document.querySelector('#invisibleGuideMeBtn').click() };
</script>
<div>
<a id="invisibleGuideMeBtn" href="#" onclick="<%= GetURL %>" target="_self" runat="server">The Link</a>
<%-- <asp:Button ID="invisibleGuideMeBtn" Text="Edit" onclick="GetURL" CssClass="btn btn-primary"/> --%>
<%-- <asp:LinkButton id="invisibleGuideMeBtn" Text="" OnClientClick="GetURL" runat="server"/> --%>
<%-- <u><b><asp:LinkButton OnClick="GetGuideMeURL" runat="server">Click here</asp:LinkButton></b></u> --%>
</div>
</asp:Content>
Above are 4 different ways I tried clicking a button/link to call the code behind. I either get the error message:
Uncaught TypeError: Cannot read properties of null (reading 'click')
at window.onload
OR the error:
The function GetURL cannot be found
I came across this error once and the following fixed it, not sure if it'll work for you.
I used <%#CSCodeName() %> this format to get the code behind and sometimes I'd have to add a semi-colon like this <%#CSCodeName(); %>
so, the page is to load, then display and THEN we are to click a button and run some code.
but, that means the page will re-load, and after page load, your code runs again then right?
so, there has to be additional information to correctly answer this question. You can certainly with ease trigger some code, and even have such code click a hidden button to run your code stub in code behind. But that of course will cause the page to post back, re-load, and now we back to after the page loads - which it just did, we going to run the code again?
So, what criteria are you to use after page load to run, or not run the code you want again? Without this information, then after page load, we click that hidden button, and then page will load again, and after page load, the code will click the button again and again, then right?

Accessing asp:Textbox value inside an asp:Datalist control using Javascript

I am having major difficulty in accessing the text value of an asp:textbox control that is inside an asp:Datalist control. Here is the code:
<asp:DataList id="UserIP" DataSourceID="dsGetData" runat="server" CssClass="lblText">
<ItemTemplate>
<span class="lblText">IP Address:</span><br />
<asp:TextBox ID="tbUserIP" class="textbox_medium" runat="server" AutoPostBack="false" Text='<%# Eval("[IPAddress]") %>' /></asp:TextBox>
</ItemTemplate></asp:DataList>
I am assigning the Textbox a value from the results of a SQL query. Then I need to get that value of that Texbox using Javascript. My JavaScript code is below:
var temp = document.getElementById("<%= UserIP.FindControl("tbUserIP").ClientID %>");
I keep getting compilation error:
The name 'tbUserIP' does not exist in the current context
Any help would be appreciated tremendously.
The problem with your code is that, when you call UserIP.FindControl("tbUserIP").ClientID the tbUserIP is not available.
Notice that, to have access to such control, you will have to invoke DataBind over UserIP DataList first and only after that, maybe you will have some results that will result in rows with text boxes called tbUserIP.
To solve that, and because there are so many ways to solve it, I suggest you give a look to this:
ASP.NET Page Event Life Cycle, so you can get a clear notion of what step are you probably missing in your way to accomplish what you want.
Alternatively, and not relying so much on the ASP.NET page processing, you can work your javascript to deal with what you know that will be the end result.
Which is:
If your DataList has results, you will have something like this <input type="text" id="$somecontainerid$1$tpUserIP" value="192.168.0.1"/> in your resulting HTML right?!
So, to grab that on your javascript, assuming you can use jQuery, you can do something like this:
// grabs all the input fields with id tpUserIP (of the multiple rows).
$ipaddressFields = $("input[id*=tpUserIP]");
// alerts each one of them, if any, to show that it works.
if($ipaddressFields.length > 0){
$ipaddressFields.each(function(){
alert($(this).val());
});
}
Here's how you'd do it in JavaScript without using JQuery. I'm not sure from where you'd call the JavaScript function. So, I'm giving you two examples. I.e. one is onclick of a TextBox and the other is onclick of a button.
Here's the HTML markup
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function Test(obj) {
alert(obj.id); // This is the ID of the textbox clicked on
alert(obj.value); // This is the value of the textbox clicked on
}
function Test2() {
var dataListid = '<%= UserIP.ClientID %>';
var obj = document.getElementById(dataListid);
if (obj != 'undefined' || obj != null) {
for (var i = 0; i < obj.getElementsByTagName('input').length; i++) { // Loop through all TextBoxes (input elements if we talk in markup language)
alert(obj.getElementsByTagName('input')[i].value); // Here are the values of each textbox
}
}
}
</script>
<form id="form1" runat="server">
<div>
<asp:DataList id="UserIP" runat="server" CssClass="lblText" >
<ItemTemplate>
<span class="lblText">IP Address:</span><br />
<asp:TextBox ID="tbUserIP" class="textbox_medium" runat="server" AutoPostBack="false" Text='<%# String.Concat("Test", (Convert.ToInt32(Container.ItemIndex)+1))%>' onclick="Test(this);" /></asp:TextBox>
</ItemTemplate>
</asp:DataList>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Test2();" />
</div>
</form>
</body>
</html>
And here's the code behind I used. You may use your own code to bind the DataList.
using System;
using System.Collections.Generic;
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> ips = new List<string>() {"1", "2", "3"};
UserIP.DataSource = ips;
UserIP.DataBind();
}
}
Hope this helped.
Cheers!

Call JavaScript function (in aspx) on aspx.cs using a button

I have this aspx:
<body>
<div>
<script type="text/javascript">
function NewPage() {
document.location.href = "http://www.nextservice.pt/"
}
</script>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Btn2" runat="server" Text="OK" onclick="Button2_Click" />
CODE1: <asp:Label ID="Label1" runat="server" Text="Label" ForeColor="#CC0000" />
</form>
</div>
</body>
and I'm working with web forms, and I wont call this button on aspx.cs
public partial class SITE_TESTER : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click (object sender, EventArgs e)
{
string code = TextBox1.Text.ToString();
if (!verifyCode(code)) // comparing users from table
{
Label1.Text = "Not Exists"; //for invalid code
}
else
{
Label1.Text = "Exist"; //for sucsseful code
/*
I Wont call my JavaScript Function here!!!!
*/
}
}
}
you can call a javascript method from server side in asp.net by following ways:
protected void button_Click(object sender , EventArgs e)
{
string jsMethodName= = "NewPage()";
ScriptManager.RegisterClientScriptBlock(this, typeof(string), "uniqueKey", jsMethodName, true);
//or
//ScriptManager.RegisterStartupScript(this, GetType(), "NewPage()", false);
}
you can use either ScriptManager.RegisterStartupScript or ScriptManager.RegisterClientScriptBlock
so difference between the two is explained below:
Let's say we have a .aspx page with the following form tag : (Line
nos. are for reference)
1. <form id="Form1" runat="server">
2. ..
3. ..
4. ..
5. </form>
Now let's look at key differences for each method :
A.
Page.RegisterClientScriptBlock() will insert the block of script
before Line 2.
Page.RegisterStartupScript() will insert the script after Line 4.
B.
Page.RegisterClientScriptBlock() should usually be used for scripts
encapsulated in functions. (hence the word "block")
Page.RegisterStartupScript() can be used for any script, even if it's
not in a function.
C.
Page.RegisterClientScriptBlock() should be used for functions that
don't need to run on Page load.
Page.RegisterStartupScript() should be used for scripts that must run
on Page Load.
D.
Page.RegisterClientScriptBlock() should be used for a script that does
not require the form elements to have been created.
Page.RegisterStartupScript() should be used for scripts that require
the form elements to have been created and uses references to them.
Notice that all the 4 differences are essentially related to each
other (they build upon the prev. one). The difference put in one line
can sometimes be too subtle.
you can know more about these from here and here
You can add a script which will be executed when page is loaded to browser:
Page.RegisterStartupScript("unique_key", "<script type=\"text/javascript\">NewPage()</script>"); // but this is deprecated function
or like this:
ClientScript.RegisterClientScriptBlock(this.GetType(), "unique_key", "NewPage()", true);
But if you simply want to do a redirect (as I can see from your NewPage function), you can do:
Response.Redirect("http://www.example.com");

Unable to read hidden field value from server side

I have a aspx page (default.aspx), inside which I am loading a user control (tree.ascx).
inside the tree.ascx there is a hidden field.
<asp:HiddenField ID="HiddenField1" runat="server"/>
I am assigning a value to the hidden field using javascript.
document.getElementById('<%=HiddenField1.ClientID%>').value = "some text here";
alert(document.getElementById('<%=HiddenField1.ClientID%>').value);
document.getElementById('form1').submit();
The alert displays the value absolutely fine. which means the value gets inserted in the hidden field properly.
But when I am posting back to server and checking the value, it is always null.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// do something.
}
else
{
string str = this.HiddenField1.Value;
}
}
My code is always getting a empty string here. somehow the postback is erasing the value from the hidden field.
What could be the reason?
Try using below syntax. It works for me even after postback.
ASPX code
<asp:HiddenField runat="server" ID="aspHiddenField" />
<input type="hidden" id="inputHidden" value='<%= aspHiddenField.ClientID %>' />
JavaScript Code
var inputHidden = document.getElementById('inputHidden');
$("#" + inputHidden.value).val("some text");
Code Behind
if (!string.IsNullOrEmpty(aspHiddenField.Value))
{
//Your code goes here
}
Check if your control is within a master page, if it is, then you need to access it like that, 1st Master Page->within master page look for the control's value, it will work surely.
Place your hidden field in update panel like :
<asp:UpdatePanel ID="UpnlHidden" runat="server">
<ContentTemplate>
<asp:HiddenField ID="HiddenField1" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
This will work for you :-)

Set always Focus on Textbox (ASP.NET, Updatepanel)

Hey,
Before I start to write my problem, I will excuse for my bad English and I hope you can understand me.
I have in a ASP.NET Webapplication an AJAX Updatepanel. In this Updatepanel is a
Textbox for dynamic search results. When I start to write in the Textbox, the results comes like Google suggest.
Now, the focus must be always on the Textbox (inputn field), now metter whereto the User clicks.
Currently the ASP.NET updatepanel refreshed after a few seconds when the User starts to type.
Thanks for help :-)
there is an event when updatepanel finish updated html dom
Sys.WebForms.PageRequestManager.getInstance().add_endRequest
try this
function EndRequestHandler() {
//get focus on the textbox
myTextbox.focus(); }
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
That is pretty fun but here is a possible solution. The idea is: if user gets out of the textbox (onblur), then take him back to the textbox (focusOnTxt function):
<head runat="server">
<title></title>
<script type="text/javascript">
function focusOnTxt(sender) {
sender.focus();
sender.value = sender.value;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="upnl" runat="server">
<ContentTemplate>
<asp:TextBox ID="txt" runat="server"
onblur="focusOnTxt(this)"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
And on Page_Load:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
txt.Focus();
}
}
A simple SetFocus f.e. in Page.Load should work:
ScriptManager1.SetFocus (TextBox1.ClientID)
UPDATE: according to this post following works...
Add this script into a script block in your page's head:
function SetEnd(TB){
if (TB.createTextRange){
var FieldRange = TB.createTextRange();
FieldRange.moveStart('character', TB.value.length);
FieldRange.collapse();
FieldRange.select();
}
}
Then add the onfocus event to your Textbox:
onfocus="SetEnd(this)"
In your codebehind's Page.Load or TextChanged-Event handler add the standard SetFocus call:
ScriptManager sm = ScriptManager.GetCurrent(this);
sm.SetFocus(myTextBox)

Categories