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
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to add new class and attributes to div if it exists on the page
I need JavaScript code on my master page which tries to find if a div exists. If so, it should add a new class and also add a new id attribute.
For example if the page has this div:
<div class="toplink">abc..</div>
Then JavaScript code should make it exactly like this:
<div class="toplink adin" data-aid="114">abc..</div>
The code inside the div should remain the same.
I tried this code but this is not working
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript">
if ($('.toplink').exists()) {
$('.toplink').addClass('adin').attr('data-aid', '114');
}
</script>
What wrong with this code? what where i placed this code,in header on footer?
Can i do this with javascript, not jquery
Instead of
.attr('data-aid','114')
use the .data method:
.data('aid','114')
http://api.jquery.com/data
Try $().length property instead, and place this snippet at the very bottom of the page, before closing body tag
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
if ($('.toplink').length > 0) {
$('.toplink').addClass('adin').attr('data-aid', '114');
}
});
</script>
Your code is probably just running before the DOM is ready. wrap as follows:
$(function() {
$('.toplink').addClass('adin').attr('data-aid', '114');
});
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>");
I got a bit of an issue in my ASP.NET MVC project.
I have a chat div in the bottom right corner (like facebook), and of course I do not want this to reload when navigating to all my navigation is ajax.
The problem I am facing is that I use the following code on the top of the view page:
<script type="text/javascript">
$(document).ready(function() {
$('#divTS').hide();
$('a#showTS').click(function() {
$('#divTS').slideToggle(400);
return false;
});
});
</script>
The problem is that this code is only loaded with ajax and does not seem to fire? I would like to run all scripts in the newly loaded view, just as if I hadn't navigated with ajax.
I cannot put this in the site.master as it only loads once and then probably the divs I am trying to hide doesn't exist.
Is there a good way to run scripts in the ajax-loaded div?
You will need to run the scripts in the success callback function of your ajax script. I would recommend you externalizing this into a separate function:
function setupEffects() {
$('#divTS').hide();
$('a#showTS').click(function() {
$('#divTS').slideToggle(400);
return false;
});
}
$(document).ready(function() {
setupEffects();
});
And in the success callback of your script call this function:
success: function(result) {
setupEffects();
}
The Masterpage gets reloaded when you navigate to another View. You can also check if a div exists with $('#div').length > 0.
By the way, "full site" ajax navigation should not be used. Reload your chat on navigation - best put it into a control (makes things easier).
I've got code like this in an .aspx file:
<script type="text/javascript" language="javascript">
function init()
{
<%= x %>
}
It works fine (x is a string that will be bound to some JavaScript at runtime), but when compiling I get an "Expected expression" warning on the <%=
I know it's not the nicest code in the world, but there are various historical bits of code that like to inject little bits of JavaScript into the page. All perfectly innocent :)
The warning is happening because the code block is inside a JavaScript <script> block; the compiler is trying to be smart about recognizing the difference between HTML/controls and JavaScript.
Although it's a bit ugly, you should be able to eliminate the warning by using eval('<%= x %>')
You might also have a look at an article I wrote on using ASP.NET to create dynamic JavaScript: http://www.12titans.net/p/dynamic-javascript.aspx
If you wanted to be perfectly legal, use a literal:
<asp:Literal ID="litX" runat="server"></asp:Literal>
and set its Text to the whole <script type="text/javascript" language="javascript">...</script> block on the server side.
Visual Studio is validating the HTML markup on the page. Strictly speaking, the '<' is not valid XHTML. This warning may be caused by a limitation of the validation as Visual Studio is interpreting the '<' character inside javascript as meaning 'less than'!
Obviously these inline expressions are not valid client code. One can change the HTML validation options in Tools|Options|Text Editor|HTML. Mind you, it may be better to simply ignore these warnings rather validate against HTML 4.01 or turn off the validation completely.
If all you're doing is adding javascript to your page, you could use RegisterClientScriptBlock to build the script server-side and then let it output it to the page.
This way you don't have to have any server-side scripting within your page and all the overhead that goes with that.
I've done this before and not had problems. However, I use jQuery's $(document).ready() instead of init(). I don't think that should be an issue, though.
What datatype is x? If it is a string, try wrapping it in single quotes, and if it's a number use the parse function for that datatype.
<script type="text/javascript" language="javascript">
var s;
var n;
function init()
{
s = '<%= x %>';
n = parseInt('<%= x %>');
eval('<%= x %>'); /* Raw Javascript */
}
</script>
Another issue would be the access level of the property. ASP.NET web forms can't access private fields directly from the code-behind. Access has to be protected or public.
Eval Javascript Function
I found the problem that I was having with this.
It seems I had incorrectly commented out HTML above the script.
<%-- <div id="directionpanel" ></div>--%>
<script type="text/javascript">
var LIST = <%= getJson()%>;
</script>
I was getting the expected expression warning on getJson()
Correctly commenting the HTML will fix the warning.
-->
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 #