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

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

Related

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.

How do I pass values from javascript (innerhtml) to asp.net codebehind without hidden input field?

I have an aspx page (mainpage), that I use to populate some divs on another aspx page (popup) on button click using the window.loaded event. Code is below:
Script on mainpage.aspx
<script type="text/javascript">
window.callback = function (doc) {
if (document.getElementById('GridView2') != null)
{
// Get Gridview HTML and wrap it with <table> tag
var temp = document.getElementById('GridView2').innerHTML;
var temp2 = "<table>" + temp + "</table>";
doc.getElementById('foo').innerHTML = temp2; // this works fine
}
else
{
// GridView is missing, do nothing!
}
}
function openWindow() {
// Only open a new Compose Email window if there is a Gridview present
if ((document.getElementById('GridView2') != null)) {
var mywindow = window.open("Popup.aspx");
}
else {
alert("Please create GridView first");
}
}
Code on Popup.aspx
<script type="text/javascript">
function loaded() {
window.opener.callback(document);
alert(document.getElementById('foo').innerHTML); //This alerts the code I need
//var input = document.createElement("input");
//input.setAttribute("type", "hidden");
//input.setAttribute("name", "testinput");
//input.setAttribute("runat", "server");
//input.setAttribute("value", document.getElementById('foo').innerHTML);
////append to form element that you want .
//document.getElementById("foo2").appendChild(input);
}
</script>
<asp:Button OnClick="Send_Email_Button_Click" ID="SendEmail" Text="Send Email" CssClass="Button1" runat="server" />
<div id="foo" runat="server">
</div>
Popup.aspx.cs
protected void Send_Email_Button_Click(object sender, EventArgs e)
{
string subject = String.Format("TEST EMAIL");
string mailto = "me#mysite.com";
string mailfrom = Environment.UserName + "#mysite.com";
string mailBody = "<h1>Testing</h1>";
MailMessage mail = new MailMessage(mailfrom, mailto, subject, null);
mail.IsBodyHtml = true;
mail.Body = mailBody;
SmtpClient smtpClient = new SmtpClient("smtphost");
smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
smtpClient.Send(mail);
}
catch (Exception ex)
{
}
}
Now, I'm stuck trying to pass the value of the div.innerhtml to codebehind, so I can create an email with this HTML markup. I tried using a hidden div, but I got an asp.net error about Request Validation: html code in an input field, which is a fair point. I can't seem to access div.InnerHtml. I get the value "\r\n\r\n". I have the value I need, but it's in Javascript, I just need a way to get this value to C# so I can send an email.
When I click on the SendEmail button, I get the alert again (because window.loaded is being called). How can I make it so that the Popup.aspx is only populate once, and not at every button click? And how to pass the innerhtml value to get SendEmail to work? Thanks so much for looking.
To send some data to code behind you have two methods. The Post and the Get.
The one is to send data with post back - meaning that you need to add them inside a hidden or other input control that send them with post.
The other is to add them to the url, as parameters.
Both of this methods can be used with ajax call. So select one and send your data to code behind.
About the message:
Request Validation: html code in an input field
This is security measure for general purpose, in your case if you know that you going to send html code on code behind, and you know how you control that, simple disabled it and do not worry - just be careful what you going to render later.
From MSDN Request Validation in ASP.NET:
This can be a problem if you want your application to accept HTML
markup. For example, if your site lets users add comments, you might
want to let users perform basic formatting using HTML tags that put
text in bold or italics. In cases like these, you can disable request
validation and check for malicious content manually, or you can
customize request validation so that certain kinds of markup or script
are accepted
Update
example code that works:
Main page
<head runat="server">
<title></title>
<script type="text/javascript">
window.callback = function (doc) {
doc.getElementById('SendBack').value = escape("<b>send me back</b>");
}
function openWindow() {
var mywindow = window.open("Page2PopUp.aspx");
}
</script>
</head>
<body>
<form id="form1" runat="server">
open pop up
</form>
</body>
</html>
PopUp Page
<head runat="server">
<title></title>
<script type="text/javascript">
function GetDataBack() {
window.opener.callback(document);
}
</script>
</head>
<body >
<form id="form1" runat="server">
<div>
<input id="SendBack" name="SendBack" value="" type="hidden" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" OnClientClick="GetDataBack()" />
<asp:Literal runat="server" ID="txtDebugCode"></asp:Literal>
</div>
</form>
</body>
</html>
and read it :
protected void Button1_Click(object sender, EventArgs e)
{
txtDebugCode.Text = Server.UrlDecode(Request.Form["SendBack"]);
}
So after a half day of breaking my head over this, I finally worked around dealing with client and server scripts by using just code-behind. I had never heard of Server.Transfer and Page.PreviousPage, so it serves me right, but it turns out it's just what I needed.
There is an excellent msdn article here that explains the concept in detail, but suffice it to say that you can access the previous page's controls if you use Server.Transfer to open the new page. Now I thought my troubles ended there, but apparently Server.Transfer is ancient and messes with the way UpdatePanel handles postbacks. Another brilliant article explaining problems and workarounds is here. I used the msdn article on PostBackTrigger to finally get my code to work.
And finally, mad props to Aristos, he sat and helped me through this, so I'm going to mark his answer as the right answer--since mine's an alternative and not the answer to my question. That's all, folks!

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

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.

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