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

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

Related

Call A Java Script Function From C# Code Behind

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.

Why IE cannot close tab on "Cancel" button click c#

I have this cancel button:
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Cancel" />
I want click that button it will close the current window, so in codebehind:
protected void Button1_Click(object sender, EventArgs e)
{
string jScript = "<script>window.close();</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "keyClientBlock", jScript);
// Response.Write("<script>parent.close_window();</script>");
}
But I do not see that window tab close in my IE browser. Is there anything can be corrected here?
Why are you doing this server side when you can just attach to the buttons click event in js/jQuery?
This probably wont work due to a browser security setting unless the window itself was spawned via the window.open() method, so you'll want to use a workaround if this is absolutely necessary.
<script type="text/javascript">
$('#button').click(function(e){
e.preventDefault();
window.open('','_self').close();
});
</script>
<button id="button" value="close" />
function CloseWindow() {
window.open('','_self').close();
}
Code Behind
protected void Button1_Click(object sender, EventArgs e)
{
string jScript = "<script>CloseWindow();</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "keyClientBlock", jScript);
}
I would also suggest to create a function in javascript and then just call it with your code, and if your not going to do anything in the .cs side us DGibs answer.

Call JavaScript function from codebehind(c#) is not working

I am trying to call a Javascript from the codebehind but form some reason it is not working. Let me explain what i am trying to accomplish: when the page loads the system needs to check if this is the first time the user visit this page. if so a lightbox will open. So I created a javascript function in the page the onPageLoad i would like to call this function if it is necesary. This is what I have so far, looks pretty straight forward but it is not working. I will appreciate any help.
Here is the
html:
<form id="form1" runat="server">
<div>
<a id="OpenTutorial" href="../lightwindow/step1.html" params="lightwindow_width=450,lightwindow_height=470" class="lightwindow page-options">Open Tutorial</a>
</div>
<script>
function OpenTutorial() { $("#OpenTutorial").click() }
</script>
</form>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
//code to check if this is the first time
.....
// it this is the first time, call this function
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "OpenTutorial()", true);
}
Maybe try using jQuery's trigger function, ie:
function OpenTutorial() { $("#OpenTutorial").trigger('click'); }
Change the id or the name of the function so they are different, they are clashing in the global namespace.
<a id="anc_OpenTutorial" />
<script>
function OpenTutorial() { $("#anc_OpenTutorial").click() }
</script>
OR just call clicking the link with the code instead of calling the function.
TO follow the link change it to access the DOM element
$("#anc_OpenTutorial")[0].click()
or
$("#anc_OpenTutorial").get(0).click()
How about refactoring your javascript function as follows?
<form id="form1" runat="server">
<div>
<a id="OpenTutorial" href="../lightwindow/step1.html" params="lightwindow_width=450,lightwindow_height=470" class="lightwindow page-options">Open Tutorial</a>
</div>
<script>
// Function that Opens the Tutorial
function OpenTutorial() {
// Using colorbox for an example, but you can start the lightbox through the function
$('#OpenTutorial').colorbox();
}
$("#OpenTutorial").click(function(){ OpenTutorial() });
</script>
</form>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
//code to check if this is the first time
.....
// it this is the first time, call this function
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "OpenTutorial()", true);
}
EDIT: Updating the OpenTutorial function to start a lightbox as opposed to opening the link

How to call method of .aspx from .cs file

I created web page in that i used javascript in .aspx file.
I have a save-button,but in the source code i used javascript for save button, where i declared a function called OnClientClick="javascript : validateTextTest()" and in the head of source code i called this function validateTextTest().
Below is the save button in source code:
<asp:Button ID="Save" runat="server"
onclick="Save_Click" Text="Save"
OnClientClick="javascript : validateTextTest()" Width="63px" />
Now i need to call a function validateTextTest() in save button of .cs file.Because i have two to three textboxs, if i leave one texbox out of three textbox it should not insert into DB.
So please tell me how to call the function in .cs file.
Insted of doing such things , you can use asp.net validation controls , for your purpose you are going to need a RequieredFieldValidator for each one of your TextBoxes , and you can use them like following code :
<asp:TextBox ID="txtISBN" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RQVISBN" runat="server" ErrorMessage="*" ControlToValidate="txtISBN"></asp:RequiredFieldValidator>
These controls are greate ! And they do validation on clientSide as you want ;)
validateTextTest is your javascript function which you probably use for some client side validations before submitting to the server. So i dont think you really should use the client side function in your sever side code (.cs file) to validate the input. You should do the same validation inside your server side code also. Something like this
if((!String.IsNullOrEmpty(TextBox1.Text)) &&
(!String.IsNullOrEmpty(TextBox1.Text)) &&
(!String.IsNullOrEmpty(TextBox1.Text)))
{
// Insert to DB
}
else
{
//Show validation error message
}
You need to firstly start off by defining the technology stack you are using. Is it ASP.NET or MVC.
I am assuming you are using ASP.NET. Given the way you have already started writing this application. You will need to do a few things to get your approach to work.
<form name="myform">
<asp:HiddenField runat="server" id="validRequest"/>
<script type="text/javascript">
function validateTextTest() {
//validation goes here
var validRequest = document.getElementById(<%#validRequest.ClientID%>);
//set validation outcome to the validRequest etc
validRequest.value = 'true';
if(validRequest.value == 'true')
return true;
return false;
} </script>
</form>
I forget which one it is but check either your Page_Load etc
protected void Page_Load(object sender, EventArgs e)
{
if(validRequest.Value == "true")
//Do whatever you need to
}

click() Event in javascript with a PARAM?

I'm using the event click() to call a method in Code Behind, like this:
HTML
<asp:button bordercolor="White" id="btnAddGS" onclick="AddGSBandeira" runat="server">
JAVASCRIPT
$("#ctl00_ContentPlaceHolder1_btnAddGS").click();
C#
public void AddGSBandeira(object sender, EventArgs e)
{
}
Its work normally, but I need to pass a param in the javascript call, like this:
$("#ctl00_ContentPlaceHolder1_btnAddGS").click("param");
But I do not know how this works ...can anybody help?
The best thing to do is create a hidden control and populate it's value with JavasScript on the click event. Your code behind will be able to access that value on your postback (AJAX or otherwise).
Markup
<asp:HiddenField ID="myHiddenField" runat="server" />
<asp:button bordercolor="White" id="btnAddGS"
onclick="AddGSBandeira"
onclientclick="SetHiddenValue()" runat="server">
JavaScript
function SetHiddenValue()
{
document.getElementById("<%=myHiddenField.ClientID%>").value = "[Your value here]";
}
C#
public void AddGSBandeira(object sender, EventArgs e){}
{
var jsVal = myHiddenField.Value;
}
You can do this with trigger.
http://api.jquery.com/trigger/
$("#ctl00_ContentPlaceHolder1_btnAddGS").trigger("click",["param"]);
I believe the 2nd parameter to trigger should be an array of arguments to pass to the function.

Categories