I have a script that I want to pop a window after 5 page views. The java script works fine on the default.aspx page with a link to call it. But I want to launce it from my default.aspx.cs page after my session var count gets to 5. How can I do this? Is it possible?
default.aspx
<script type="text/javascript">
window.name = "Register";
function popWin(link) {
var w = window.open(link.href, link.target, 'width=500,height=600,resizable');
return w ? false : true; // if popup blocker, use the default behaviour of the link
}
</script>
Default.aspx.cs page
if (Session["PagesViewed"].ToString() == "5")
{
//Call my Javascript function How?????
}
You can output javascript into a LiteralControl from your code behind:
.aspx:
<asp:Literal id="myLiteral" runat="server" />
Code behind:
myLiteral.Text = "<script type='text/javascript'>popWin('url');</script>";
When rendered this way, the output script will call the function - make sure it is lower in the page than where the function was defined to ensure it exists.
In ASP.Net you can do the following:
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"openpopup",
"popWin('www.someurl.com');",
True);
If you need more control over your scripts placement #Oded has a better approach - as trying to call a function that has not been defined isn't a good idea...
You cannot call javascript functions directly from C#. However, what you could do is pass a <script> to the browser that executes the function.
response.Write("<script>popWin(something);</script>");
Related
I need to print a DataViewGrid from a website made in ASP.NET and have am using JavaScript to do it as it seems much easier that achieving it is C#. Below is the code that I am using to try and print the document.
<script type="text/javascript">
function doPrint() {
var prtContent = document.getElementById('<%# dgvInvoices.ClientID %>');
prtContent.border = 0;
var WinPrint = window.open('', '', 'left=100,top=100,width=1000,height=1000,toolbar=0,scrollbars=1,status=0,resizable=1');
WinPrint.document.write(prtContent.outerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
I had to change line 3 from ('<%= dgvInvoices.ClientID %>'); because it was giving me a control error, and now I believe this is stopping my document from printing. Does anyone have any work around or fixes for this? Or an easy way to print in C#?
The original error was:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
If you are using ASP.NET Ajax and have a ScriptManager in your page or master page, you could do:
var prtContent = $get('<%= this.dgvInvoices.ClientID %>');
Also, if you are using the .Net framework version 4 or above, you can set the property ClientIDMode="Static" in the control, so the ClientID will be rendered as declared and you'll be able to use the document.getElementById javascript function passing the declared ID as parameter.
I have a page that contains a user control within an update panel. $(document).ready(function() ) { is called and executes the code correctly when the page firsts loads but if the user clicks a button (within the user control), the document.ready() doesn't get called (document.load, onload also don't work)
I have researched this on the net and found similar problems but nothing that can explain why this isn't working. What other causes can there be for document.ready not working?
This will be a problem with partial postback. The DOM isn't reloaded and so the document ready function won't be hit again. You need to assign a partial postback handler in JavaScript like so...
function doSomething() {
//whatever you want to do on partial postback
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(doSomething);
The above call to add_endRequest should be placed in the JavaScript which is executed when the page first loads.
Instead of $(document).ready you could use function pageLoad(){}.
It's automatically called by the ScriptManager on a page, even on a postback.
I've run into this a while ago, as El Ronnoco said, it has to go with the DOM not being reloaded. However you can simply change
$(document).ready(function() {
to
Sys.Application.add_load(function() {
This will force it to run on every postback.
You can use function pageLoad() as well, but you can only have one pageLoad function, whereas with Sys.Application.add_load, you can add as many handlers as you wish.
Bestest way is
<asp:UpdatePanel...
<ContentTemplate
<script type="text/javascript">
Sys.Application.add_load(LoadScript);
</script>
you hemla code gose here
</ContentTemplate>
</asp:UpdatePanel>
Javascript function
<script type="text/javascript">
function LoadScript() {
$(document).ready(function() {
//you code gose here
});
}
</script>
or
Its under UpdatePanel than you need to register client script again using
ScriptManager.RegisterClientScript
or
$(document).ready(function() {
// bind your jQuery events here initially
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
// re-bind your jQuery events here
loadscript();
});
$(document).ready(loadscript);
function loadscript()
{
//yourcode
}
This is an example that worked for me in the past:
<script>
function MyFunction(){
$("#id").text("TESTING");
}
//Calling MyFunction when document is ready (Page loaded first time)
$(document).ready(MyFunction);
//Calling MyFunction when the page is doing postback (asp.net)
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(MyFunction);
</script>
This code below works nice to solve this problem. As indicated in link posted before (http://encosia.com/document-ready-and-pageload-are-not-the-same/), when you have an asp.NET with updatePanels you shall use function pageLoad(). When you have only one page and in each postback it will be fully reloaded, the $(document).ready() is the right option.
Example using pageLoad:
function pageLoad() {
$(".alteraSoVirgula").keyup(function () {
code here
})
}
I was also facing the same problem but i found the jQuery $(document).ready event handler works when page loads, but after ASP.Net AJAX UpdatePanel Partial PostBack it does not get called. so use Sys.Application.add_load(function(){}); instead of $(document).ready.
This works perfectly for me :)
<script>
Sys.Application.add_load(function() {
//Your code
});
</script>
$(document).ready(function () {
PreRoles();
});
//On UpdatePanel Refresh
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm.add_endRequest(function (sender, e) {
if (sender._postBackSettings.panelsToUpdate != null) {
PreRoles();
}
});
};
function PreRoles() {
// Add codes that should be called on postback
}
Most of the times, this is happening because of the Updatepanle.
Just put postback triggers to the button and it will solve this.
I am trying to put a c# code when a js function happens.
I found this article https://www-archive.mozilla.org/js/spidermonkey/tutorial.html
but I didn't fully understand how to do it in my case.
Here is what I tried.
rooms.aspx
<script type="text/javascript" language="Javascript">
function DetectBrowserExit()
{
// alert('Execute task which do you want before exit');
<%
if(Application["player1"]==Session["mynick"])
{
Application["player1"]="";
Application["status1"]=false;
}
%>
}
window.onbeforeunload = function () { DetectBrowserExit(); }
</script>
All that goes in the head of the aspx and DetectBrowserExit happens when a user closed the browser.
You know how to make the C# code accessible?
Thank you.
You can use page methods with a script manager to do this.
Using Page Methods in ASP.NET AJAX
I'm sure this is fairly straightforward but i'm having trouble getting it to work. I want to add a javascript function to my page, but only when the page postsback.
So I have a button that calls some server-side code, and when it is finished and the page is re-loading I want the javascript function to be called.
Thinking about this i guess I could just add a hidden variable and set it when the button is clicked, but i think i'd rather just insert the javascript onto the page when it is loading back.
Is this possible, or even a good way to do it?
Thanks,
Neil
Edit: Okay this is my OnClick method in the C# code.
protected void Save(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "<script type=\"text/javascript\">alert('hello world');</script>");
EnforcementMatch(false);
EnforcementMatch(true);
ApplicationNotMatch();
ApplicationMatch();
Response.Redirect(Request.Url.ToString());
}
Another Edit: Just realised that the response.redirect at the bottom reloads my page cancelling out the code I put in, duh!
You can use ClientScriptManager.RegisterClientScriptBlock
http://msdn.microsoft.com/en-us/library/btf44dc9.aspx
If you place it on the button click event, you don't have to worry if it's a postback or not.
You know about the IsPostBack function, right?
IsPostBack (MSDN)
if (IsPostBack)
{
ClientScript.RegisterClientScriptBlock()
}
This script will be fired with every single postback from updatepanel
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
alert('hello world');
});
</script>
Place it in a separate script block, only to be rendered on postback.
<script type="text/javascript" runat="server" visible="<%#this.IsPostBack %>">
TheCode();
</script>
I'm having problems using JQuery inside an ASP.Net User Control I've created a sample and here is the markup for my user control:
<%# Control Language="C#" ClassName="UC" AutoEventWireup="true"
CodeFile="UC.ascx.cs" Inherits="UserControls_UC" %>
<span id="Licenses"></span>
<script type="text/javascript">
$(document).ready(function() {
var ctlID = $("span[id$='Licenses']");
ctlID.text = "Testing";
});
</script>
If I include this script tag <script type="text/javascript" src="js/jquery-1.3.2.js" /> in the aspx file containing the user control to reference JQuery, nothing happens. If I don't include it, I get a JavaScript error dialog saying there was a runtime error and that an Object was expected. Any ideas what I may be doing wrong?
text is a function in jQuery. Try:
ctlID.text("Testing");
Prefixing the '$' to the id gets all elements that ends with "Licenses" .
Make a quick change to test this to '#' will get you exactly one element.
$(document).ready(function() {
var ctlID = $("#Licenses");
ctlID.text = "Testing";
});
To make it work with attribute selector try
$('span[#id=Licenses]') // You can omit the # in the latest version of jquery.
I think you should use something like this:
var ctlID = $("span[id$='Licenses']").get(0);
ctlID.text = "Testing";
Have you included the jquery library correctly on master page?
Is that not meant to be dollar before id, i.e. $id='Licenses' ? or even a #