dynamic Javascript in asp.net - c#

well. The problem i'm facing is i have my own custom control and i do a query , get records and dynamically add html controls to the page based on the data.
Now there's the problem of adding some dynamic javascript
I do this with the help of literal controls.
<asp:Literal runat="server" ID="latEventToolTipJqueryScripts"></asp:Literal>
This works like a charm
<script language="javascript" type="text/javascript">
// <![CDATA[
Sys.Application.add_load(WireEvents_<%=this.ID%>); // fix wiring for .NET ajax updatepanel
$(WireEvents_<%=this.ID%>); // handle page load wiring
function WireEvents_<%=this.ID%>() {
<asp:Literal runat="server" ID="latEventToolTipJqueryScripts"></asp:Literal>
}
// ]]>
</script>
I add the literal text dynamically from code behind.
However, when placing the control in an updatepanel, the postbacks don't update the script.
EDIT: The Sys.Application.add_load rewires the necessary functions just fine with the updatepanel. The problem is that the script that needs to be in place of the literal, doesn't update when in an updatepanel.
I've tried the ClientScript.RegisterStartupScript but it has the same effect as with the literal control trick. Any help?
---------------------------SOLVED (tnx to Pranay Rana)----------------------------------
Got rid of the literal in the ascx side. as well as the Sys.Application.add_load
now it's only in the code behind. The thing that was throwing me off was the JQuery thing.
this.strBuilderJS.Append( "<script language='javascript' type='text/javascript'>" +
"$(WireEvents_" + this.ID + ");" +
"function WireEvents_" + this.ID + "(){"+
" alert('stuff');");
this.strBuilderJS.Append( "}</script>");
and then
ScriptManager.RegisterStartupScript(this, this.GetType(), "strBuilderJS", strBuilderJS.ToString(), false);

Make use of ScriptManager.RegisterStartupScript() to register your script...may resolve problem ...
Check this resolve your problem : Add JavaScript programmatically using RegisterStartupScript during an Asynchronous postback

I would recommend on a different approach. To create a dynamic javascript for any language. I would create a reference to a dynamic file. For this example I will use .NET
Create a test.aspx page and add this script:
<script type="text/javscript" src="js/foo.aspx"></script>
Make sure your page response with the right content type. So for this instance I would add this on page load code behind for your foo.aspx:
Response.ContentType = "application/javascript";
On the foo.aspx html view add your javascript code.
alert("<%=DateTime.Now%>");
Browse your test.aspx page and you should see an alert with the current date
You should be able to move forward from here. The goal is to separate the javascript file from the static page.
Happy Coding.

How to change text of ASP Button control on anchor tag click
We have an ASP Button below and we want to change text when WE click on anchor tag
<asp:Button ID="btn_Add" runat="server" CssClass="button2" onclick="btn_Add_Click"/>
We have following two anchor tags
Add New
Add New
Now we add following code in script tag
<script type="text/javascript" language="javascript">
function changeText1() {
document.getElementById("lbl_header").innerText = 'Add New Teacher';
document.getElementById("btn_Add").value = 'Add';
}
</script>
<script type="text/javascript" language="javascript">
function changeText2() {
document.getElementById("lbl_header").innerText = 'Delete Teacher';
document.getElementById("btn_Add").value = 'Delete';
}
</script>

Related

Hide URL when mouse hover over asp:HyperLink

I have seen javascript:void(0) method used on <a> tags in HTML to hide the target URL of the hyperlinked object. Now I want to do the same on a <asp:HyperLink>, what should I do?
I am doing ASP.NET and here's the markup:
<asp:HyperLink runat="server" ID="hl1">Blah blah blah</asp:HyperLink>
In the codebehind I specified the NavigateUrl for hl1 using HttpUtility.UrlDecode method.
I tried hl1.Attributes[href]="javascript:void(0)"; in coebehind, does not work. Cannot open the NavigateUrl anymore.
You need to store the url you are wanting to navigate to in a hidden field and just set NavigateUrl = "#" in the markup as shown below. This way when user's cursor hovers over the link, the actual navigate URL will never be displayed at bottom of browser.
Then attach a click event handler on client-side for the hyperlink which you do by just setting onclick attribute of the hyperlink to a JavaScript function called navigate. The actual redirection to a new page is done by this navigate function.
In this situation, you will only see the URL of current page suffixed with #. For example, if your current page URL is http://localhost/mysite/view.aspx then it will show http://localhost/mysite/view.aspx# at bottom of browser.
Markup needed
<asp:HyperLink runat="server" ID="hl" NavigateUrl="#"
onclick="navigate();">Some Text</asp:HyperLink>
<asp:HiddenField ID="hdnURL" runat="server" Value="http://www.microsoft.com" />
JavaScript needed
<script type="text/javascript">
function navigate() {
window.location.href = document.getElementById("<%=hdnURL.ClientID%>").value;
}
</script>
Another approach that you can use if you must set the NavigateURL for the hyperlink in code-behind is as below. In this approach, you need to remove the NavigateURL before the content renders and store it in a global variable called linkUrl. The event that fires before the content renders is pageLoad and we will use that event to do this hack.
Global variable in JavaScript must always be declared outside all methods.
Then on clicking the hyperlink, we can obtain the value from the global variable of linkUrl and redirect user to that location.
Note: Keep the markup of the hyperlink the same as in first approach. But remove the hidden field from that markup.
<script type="text/javascript">
function navigate(event) {
window.location.href = linkURL;
}
var linkUrl = null;
function pageLoad() {
var link = document.getElementById("<%=hl.ClientID%>");
linkURL = link.getAttribute("href");
link.setAttribute("href","#");
}
</script>

Variable from javascript function in aspx page accessible in c# code in same javascript function

My code in aspx page is:
<script type="text/javascript">
function MenuItem_Click(itemId) {
<%
MyAspLogger("Clicked on item: {0}", itemId);
%>
}
</script>
I don't know how to access "itemId". I know that from other side - accessing c# variable in aspx code it is possible. But I don't know if is possible access javascript variable in c# code include in same javascript function.
Thank you for your help.
I guess you are tryingto get the clicked menu ids, and then log all clicked menu item?
1- To get the menu id,
Pass the menu object using keyword "this" to the function handling the click (MenuItem_Click).
<a id='menu_1 onclick='return MenuItem_Click(this);'>Click Me!</a>
<script type="text/javascript">
function MenuItem_Click(me) {
alert(me.id); // The Id of menu clicked.
// Do Whatever you want with the id now.
.
.
.
}
</script>
2- Logging clicked menu id
You have 2 options actually ... use a web-service call each time a menu clicked (which I don't recommend)
OR
Use a variable to store the clicked menu ids Or a hidden variable.
<script type="text/javascript">
function MenuItem_Click(me) {
var hdnMenuLog = document.getElementById('hdnMenuLog');
hdnMenuLog.value = hdnMenuLog.value + '|' + me.id;
}
</script>
Hope this helps!
You can not access javascript variable value in server side code until you do postback and send asnc call using ajax. Asp.net generates html and javascript code from server side and sends response to client i.e. browser.
To access javascript variable value after postback you can assign it to some hidden field that is made server accessible and access it on server side code. This is how asp.net maintains ViewState.
I tried
<asp:Label CssClass="helperLabel" runat="server" Visible="False">Test</asp:Label>
<script type="text/javascript">
function MenuItem_Click(item) {
// Setup
$(".helperLabel").html("asdf");
<%
MyAspLogger("Clicked on item");
%>
</script>
in code behind I have
protected void MyAspLogger(string logMessage)
{
MyLogger.Debug(logMessage + "/" + helperLabelId.Text);
}
It's working fine but 2 other issue.
Text is not change on server side but only on client side(saw that after removed Visible attribute from asp control).
And also I found that MyAspLogger method is called on page load not after click event.
What I need is grabb itemId and log that via my Logger method from code behind.
Thank you.

Setting Scroll Position on PostBack

I am writing in asp.net c# code.
I want to control the page position on a post back. Neither MaintainScrollPositionOnPostback equal true or false, is what I want. True is too low and False is too high. Another problem is that the position should be different depending on which control is press. A third issue is that MaintainScrollPositionOnPostback=true works in I.E. but not in Firefox.
Want I want is similar to the href related tags e.g. <a href="#body2"> except in code.
Thanks for any suggestions.
Assuming you are able to use JQuery, try the following:
http://abeautifulsite.net/blog/2010/01/smoothly-scroll-to-an-element-without-a-jquery-plugin/
Just inject script and pass the ID of the control that fired your postback event.
If you cannot use jquery for some reason, here is a less elegant approach:
http://clifgriffin.com/2008/10/14/using-javascript-to-scroll-to-a-specific-elementobject/
Edit (Samples):
Here is an example of straight html using the jquery method, presuming you have a script file named jquery.js in the same folder as the html page.
<html>
<head>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('html,body').animate({
scrollTop: $('#scrollHere').offset().top
}, 0//increase for smooth, visible scroll
);
});
</script>
</head>
<body>
<div style='width:100px; height:1000px; background-color:red;'>
top filler
</div>
<a id='scrollHere' href='#'>Scrolls to this element</a>
<div style="width:100px; height:1000px; background-color:blue;">
bottom filler
</div>
</body>
</html>
Here is an example of a client-side method that you can pass the "ClientID" property of any visible page control and it will register the javascript to scroll to the element on page load (assumes jquery is registered on the page and only registers one call per request):
private void ScrollToControl(string controlId)
{
//scroll to button
string script =
"$(document).ready(function() {" +
"$('html,body').animate({ " +
"scrollTop: $('#" + controlId + "').offset().top " +
"}, 0);" +
"});";
if (!Page.ClientScript.IsStartupScriptRegistered("ScrollToElement"))
Page.ClientScript.RegisterStartupScript(this.GetType(), "ScrollToElement", script, true);
}
If you know specific pixel values where you want your window to be then you can try using window.scrollTo() function in Javascript.
window.scrollTo(0,0);
Maintain page scroll position on button click by:
$("#Next").click(function() { $('html,body').animate(
{ scrollTop: $('.required').offset().top
}, 0//increase for smooth, visible scroll ); });

asp.net accessing javascript variables after ajax updatepanel

I'm using AJAX on an ASP.NET web project to update a page. Some of my functions return XML that I want to embed on the page after it reloads. This part works, here's a sample of how it looks at the top of the page:
var productXML = "<?xml version=\"1.0\"?><ArrayOfProduct xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Product><ActualProdID>123</ActualProdID><Name>Test</Name><Description>Test</Description><Edition>Test</Edition><Platform>Test</Platform><Family>Test</Family><Type>Test</Type><DeploymentTypes>Test</DeploymentTypes><BaseActualProdID>Test</BaseActualProdID><Price>0</Price></Product></ArrayOfProduct>";
Later in the page I'm trying to use the XML but it's not working. I tried to do something simple and just throw an alert box in that looks like this:
<script type="text/javascript">
function closeLoading()
{
jQuery('.pleaseWaitPanel').css({ 'display': 'none', 'visibility': 'hidden' });
alert("here");
alert(productXML);
alert("here2");
}
</script>
closeLoading() is called inside:
window.onload = function () { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading); };
It loads the jQuery and the first alert "here" works perfect. When I go to alert the productXML, nothing happens. It doesn't throw a JavaScript error, I'm using Firebug. I can confirm the XML is on the page.
Any help on this would be GREATLY appreciated!!
From your code snippets, it looks like your closeLoading function is only being called in your window.onload function. This means that it won't be called after any Ajax request completes as the window won't be reloaded.
I would try moving your call to Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading) to just before your closing server-side form tag:
<form runat="server">
...
<script>
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading);
</script>
</form>
Hope this helps.
var productXML
Is a ServerSide variable, so you don't have access to this in Client script.
If you want to use in a javascript function you can do this :
1) Put the result in a textbox hidden, like
<input type='hidden' value='<%=productXML%>'>
then simply get the value of the textbox.

C# asp.net calling javascript

I have a div inside asp:content :
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="slidebar" style="display:none;" >There are some pending approvals.Please approve by the 25th of this month
Click here to close <sup style="font:caption;color:#373636;">X</sup>
</div>
<script language="javascript" type="text/javascript">
function showbanner()
{
document.getElementById("slidebar").style.visibility="visible";
}
</script>
<\asp:content>
and the code behind:
ClientScript.RegisterClientScriptBlock(Page.GetType(), "displaybanner", "return showbanner();", true);
I cannot call the function showbanner from the code behind and even when I directly call the statement inside showbanner with registerclientscript ...it doesnt get called .
Please help
The properties visibility and display are not the same, change the js function to:
function showbanner()
{
document.getElementById("slidebar").style.display="block";
}
also change your code behind to
ClientScript.RegisterStartupScript(Page.GetType(), "displaybanner", "showbanner();", true);
so the script executes after the page has load or else it won't find the element.
I'm not sure why your register script isn't working but have you tried putting the javascript call directly on the page inside a script block? If that works then wrap the script block in a pannel at the bottom of the page with visible="false". In your code behind when you determine that you want it to work set the visibility to true.
If you are using Jquery I would also wrap the contents of your script block in:
$(document).ready(function() {
//javascript call here
});
Just to make sure it doesn't get called before the page can actually handle it.
This all assumes of course that your function call is good and that the issue is with register client script.
Okay one of my team mebers Mahi came up with a solution...rather than CleientScript.reg.....
we used Page.RegisterStartupScript and it works fine :))

Categories

Resources