C# asp.net calling javascript - c#

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 :))

Related

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.

How to call javascript function from code-behind after ajax postback

I'm using Telerik controls in my project and I am using RadTabStrip for my purposes
<telerik:RadTabStrip ID="tsRequisitions" Skin="" MultiPageID="mpRequisitions" runat="server" Width="980" ScrollButtonsPosition="Right" ScrollChildren="True" OnTabCreated="tabCreated">
As you can see in this template I call tabCreated method every time when new tab has created. Now I want to call some javascript function from server-side(all mentioned is in RadAjaxPanel).
I've tried to use RegisterClientScriptBlock, but it didn't help me to fire my javascript function.
if (!ClientScript.IsClientScriptBlockRegistered("tabSelected"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(),
"tabSelected", "TabSelected();", true);
}
And I have this in my .aspx file
<script type="text/javascript">
function TabSelected() {
console.log("dfgdfgfdg");
}
</script>
How can I call my function from code-behind after AJAX postback?
The following code snippet do the trick
RadScriptManager.RegisterStartupScript(this,this.GetType(), "tabSelectedScript", "TabSelected();", true);
RegisterStartupScript is static method of RadScriptManager class (I'm using Telerik controls here again, but maybe it will work with asp.net standart ScriptManager too).
Have you tried this ?
Page.RegisterStartupScript("OnLoad", "<script>TabSelected();</script>");

ASP.net user control doesn't call a javascript function

I am developing asp.net web application, I have a repeater that call a registered user control, I have in the user control a button that I want to call a javascript function that make Ajax call to do some action on server. this button doesn't call the javascript method, I don't know why? and when I view source I found the javascript function is repeated for every item in the repeater, how to eliminate this repetition specially that I read server items inside the function, and why the function is not called?
Thanks a lot!
sercontrol.ascx
<div id="divBtnEvent" runat="server">
<input type="button" id="btnAddEvent" class="ok-green" onclick="saveEvent();" />
</div>
<script type="text/javascript">
function saveEvent()
{
var eventText = document.getElementById('<%=txtEventDescription.ClientID%>').value;
// make ajax call
}
Problem 1: In view source I found the javascript function is repeated for every item in the repeater.
Solution:
Put your js function on the page on which the user control is being called. You also have to place your js files references on your page not on user control.
Problem 2: You are trying to get control's value as <%=txtEventDescription.ClientID%>.
And I think, this control is on user control.
Solution: Please check your page source code and see that the control's actual clientid is.
If still have issues in calling js function, check firefox's Error consol.
Hope this help.
OP said and when I view source I found the javascript function is repeated for every item in the repeater
to get rid of it put ur javascript as follows
<head runat="server">
//heres goes ur js
</head>
I guess that's ur problem
Replace the saveEvent function definition from user control onto the page where the control is used. All the way as I understand, you have use in this function textbox id from that page.
Actually, if you have place javascript block in user control's markup it will be rendered along with the rest control's markup. To avoid this you may register javascript from the server code and check is that code block is already registered.
By the way, as it is - only the last function definition being taked into attention as it redefined the previous one each time new control instance rendered.

dynamic Javascript in asp.net

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>

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.

Categories

Resources