asp.net accessing javascript variables after ajax updatepanel - c#

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.

Related

Razor server side code block and Jquery

My application is MVC5 c#, trying to execute the following:
#{
var s = Model.PhysicalExam;
if (s == null)
{
<script>
alert("1");
$("#newSale1").hide();
</script>
}
else
{
<script>
alert("2");
$("#newSale1").show();
</script>
}
}
Alert works, however does not hide or show the button. Would appreciate your suggestions.
I would guess that newSale1 maybe isn't loaded in the DOM when that script code is executed. You should probably put those blocks inside a document ready event.
$( document ).ready(function() {
console.log( "ready!" );
});
I might go with something like this at the bottom of the page
<script type='text/javascript">
var isExamNull = #((Model.PhysicalExam == null).ToString());
$(document).ready( function(){
if (isExamNull)
$("#newSale1").hide();
else
$("#newSale1").show();
};)
</script>
Putting scripts at the bottom of the page lets the html render first, $(document).ready ensure that, well, the document is ready. Using the #() will write your server side values into your scripts, another technique is to use a hidden and have the script check the value of the hidden.

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 Refresh base page from iframe

I have page with other asp.net page inside iframe.
And on button click inside iframe i need to refresh main page from server side.
How can it?
Make use of javascript and you can easily do it
call the following function on your button click
<script language="javascript">
function RefreshParent()
{
window.parent.location.href = window.parent.location.href;
}
</script>
From the cs code if you are opening the aspx page in the iframe
Page.RegisterStartupScript("RefreshParent","<script
language='javascript'>RefreshParent()</script>");
Its explained very well in the following links:
link 1
link 2
Hope it helps.
For some reason the javascript function shown in earlier answers did not work for me (although the function was called). However, this worked for me:
function RefreshParent()
{
// Was: window.parent.location.href = window.parent.location.href;
parent.location.reload();
}
I had to add it near the start of my HTML (near the end of the HTML didn't work, as it was not yet rendered).
I used this C# code to call it, which is based on earlier answers but updated to use the current API which has an extra initial paramter, "type":
ClientScript.RegisterStartupScript(this.GetType(), "RefreshParent", "<script language='javascript'>RefreshParent()</script>");

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

anchor text onclick to c# function

i have an iframe that which source need to be updated and refreshed. the way i want to do it is to click on an and with it's onclick function, i need to send something like myiframe.Attributes["src"] = "blah.aspx";
is there any quick way to do this?
thanks in advance
You can use javascript to send an AJAX query back to the server with the frame's source.
The javascript you could use is iframe.location.href where 'iframe' is the id attribute of your iframe.
Then you can send a callback to the server using ASP.NET AJAX (or another ajax call if you wish). Here is a good tutorial: http://ajax.net-tutorials.com/
You could do it all client side if you wanted to (untested code):
...
<body>
<a id="yourAnchorId">Load It</a>
<iframe id="youriFrameId" src="blank.html" width="500" height="400"></iframe>
<script type="text/javascript">
document.getElementById('yourAnchorId').onclick = function() {
var frame = document.getElementById('youriFrameId')
frame.src = "blah.aspx;"
frame.location.reload();
};
</script>
</body>
...

Categories

Resources