Execute jquery on first page visit - c#

I have the following code on my Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "$('#sd').slideToggle(200);", true);
}
This is a jQuery call to toggle the visibility of a div with the id #sd.
This seems to work only when this.Page.IsPostBack == true?
I have a simple form on that page that works as expected.
The form contains an input field that gets processed and returns the result.
That works.
However, now i would like to add an option to access the page with the (input) parameter in GET, so processsing could be done on first visit.
What is wrong and why is it not working on first visit?

I found it.
Typically, after I posted a question on line:
I moved this code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.flexibleArea.js"></script>
to after the title tag.
It seems like #sd wasn't being loaded at the time of the call.
Could anyone shed more light on this?

Related

Call a javascript function from c# to replace a div

i have a web page in c#, in the codebehind i generate a url, on the aspx page i want to update an iframe to show this url.
after looking a while for the means to do this, i found i can register javascript to force the refresh of the iframe, but now i am experiencing a trouble.
no matter what i try, the url seems to never change, remaining at the on load defined url.
let me show you some of the code so you can see what i am doing and maybe help me with thi issue.
i have this string, who handles the url i want to go
public String currentMap = "google.com";
this is the function who registers the javascript
protected void Page_Load(object sender, EventArgs e)
{
UtilityClass utility = new UtilityClass();
this.Page.ClientScript.RegisterStartupScript(
this.GetType(),
"StartupScript",
"Sys.Application.add_load(MyLoad);",
true);}
this registers the javascript function, this function is suppoused to load a modified url, like this
<script type="text/javascript">
function MyLoad(sender) {
$get('maps').innerHTML += "<%= currentMap %>";
}</script>
while i can see how i the inner html updates (you can see i use the =+ operator, because i wanted to see if i was adding something to the page), but the value for currentMap is always the same, and the iframe does not gets updated.
i launch a function, when i click an object in a gridview, this function does something like this.
currentMap = "<iframe src=\"somepages.html" id=\"viewerframe\" width=\"100%\" height=\"450\"></iframe>"\"";
i can see the iframe updating, but the value remains at http://google.com (a test value hard coded).
how can i update the div so it shows the correct url in the iframe?
thank you for the help
To update the src of an iframe you can use this code:
//Set upload frame source
var uploadUrl = '/Profile/upload.aspx?id=' + $.url().param('id').replace('/', '');
$('#uploadFrame').prop('src', uploadUrl);

How to load javascript function from an dynamicall added control?

The Master page got a ScriptManager.
Then i got a Control with a ScriptManagerProxy and an UpdatePanel.
Inside the UpdatePanel there I dynamically add a Control (also containing a ScriptManagerProxy) and from that control I need to run some JavaScript code.
DynamicControl.ascx:
<script type="text/javascript">
function doSomething() {
alert(1);
}
</script>
DynamicControl.ascx.cs:
public void Page_Load(object sender, EventArgs e)
{
...
ScriptManager.RegisterStartupScript(
this.Page, this.GetType(), "scriptID",
"<script type='text/javascript'>doSomething();</script>", false);
My problem is that the function "doSomething()" is never called and i dont know why. :S
Edit: It is called but not directly when i add the control.
If I do code like this, there will be an alertwindow:
"<script type='text/javascript'>alert(1);</script>"
Ok I think i need to add some more information:
The control is dynamical added inside a jQuery Dialog. And I found out that the javacode is first executed after i close and then open the dialog. Some kind of event is triggered so that the code is executed there i think. Is it possible to force this event? so the scripts are executet directly when the control is added ?
placeHolder.Controls.Add(dynamicReportControl);
This c# code doesn't execute the javascript tag immediately ?
Please try something like this
ScriptManager.RegisterStartupScript(
this.UpdatePanel1, this.UpdatePanel1.GetType(), "scriptID",
"<script type='text/javascript'>doSomething();</script>", false);
Where UpdatePanel1 is your UpdatePanel
Try setting the addScriptTags argument to true, and remove the script declaration from your code.
Is that code only supposed to run on every request? If so, why not just add this code to the ASCX:
window.onload = doSomething();

Run Javascript After Page Load

I understand there are MANY posts on this, but I have tried every single one and none of them work!
I have an aspx and aspx.cs page being run using visual studio 2010.
on my aspx page I have a table
<table id="viewPendingTable" runat="server"></table>
On the aspx.cs page, the table is loaded with data. This works fine, No Problem. Once the page is loaded, the table contains the dynamically added data I require.
I am using jquery dataTables to style my table using the standard
$(document).ready(function () {
$('#viewPendingTable').dataTable({
"bJQueryUI": true,
});
});
When I create a test table with dummy information directly into the html, the data table displays correctly as required. But when I apply The jquery script to the dynamic table. Nothing happens. The dynamic data is displayed as required, but the data table (search functions, style etc) are not present.
Now I suspect this is because the scripts are run before the table is populated with data.
This is where I began my mission to force the jquery/javascript to run AFTER the aspx.cs has run and the table has been populated.
But I failed... So just as a test I thought I'd run an alert('YAAY'); from the c# side using registered start up scripts. but to no Avail that wouldnt work.
So can somebody PLEASE tell me why this isn't working.
I've tried Multiple Different ways of startup scripts!
My aspx is:
<table id="viewPendingTable" runat="server"></table>
<script type="text/javascript" language="javascript" id="ShowTable">
<!--
loadTable();
function loadTable() {
$(document).ready(function () {
$('#viewPendingTable').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
});
alert('ALEX');
document.getElementById("table_id").width = "100%";
}
//-->
</script>
And my aspx.cs is:
protected void Page_Load(object sender, EventArgs e)
{
loadMyTable();
ClientScriptManager a = null;
a.RegisterStartupScript(GetType(), "anotherkey", "alert('ASDFASDFASDF');", true);
a.RegisterStartupScript(GetType(), "anfgsdgsderkey", "alert('MOTHER');", false);
a.RegisterStartupScript(this.GetType(), "AKey", "loadTable();", true);
ClientScript.RegisterStartupScript(GetType(), "MyScript", "<script language=javascript>" + "alert('Hello ASP.NET'); }</script>");
ScriptManager.RegisterStartupScript(this.Page, GetType(), "script", "alert('Success!');", true);
Page.ClientScript.RegisterClientScriptBlock(GetType(), "script", "alert('AAA');", true);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "script",
"alert('a');" +
"$(document).ready(function (){" +
"$('#viewPendingTable').dataTable({" +
"\"bJQueryUI\": true" +
"\"sPaginationType\": \"full_numbers\"" +
"});" +
"}); alert('b'); document.getElementById('viewPendingTable').width = 100%", true);
}
I have tried more methods for trying to run javascript after page load but they were lost in the anger of failing so badly.
Somebody PLEASE HELP!
Why aren't my simple javascript alerts running?
Even if I got them to work... would the data table be correctly styled by executing the jquery after page Load???
Thankyou Kindly for your time
Alex
p.s. No comments on asp:gridView or asp:DataTable as That Failed EPICALLY and i posted a question on it days ago and nobody has replied. If you care to take a look
CLICK HERE
Change this line of code and try
"$('# " + viewPendingTable.ClientID + "').dataTable({" +
in you document.read script that you have written
Its because you can get acutal ID of the table control when the page get render on the browser
Edit
Make use of
RegisterStartupScript because it emits your JavaScript at the end of the page just before </form> tag (before the <form> tag ends).
The most likely issue you're facing is that id="viewPendingTable" doesn't exist on your page.
By adding the runat="server" attribute on your table, the ID will be changed so that ASP.NET can bind to it on postback.
You'll need to use the ClientID property of the table in your jQuery:
viewPendingTable.ClientID
First of all, client side code is ALWAYS run after the server side code is executed. Although client side code can be run before the html is rendered in your browser. So this has nothing to do with that.
If you check the generated html, you will see that asp.net will generate the id's voor the element to which you apply the runat attribute. To solve this, add a class to the table and change your js selector to $(".classname").
Extra tip: Use a debugger like firebug which allows you to debug your js code, which makes it easy to solve problems like these :)

insert javascript only on page postback

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>

How do I ensure javascript is fired after an update Panel has, well, updated?

Morning all.
How are we? Excellent I hope.
I have the following little bits of code that I am using to check/uncheck a couple of radio buttons on my page:
<script type="text/javascript">
function SetOption1RadioButton() {
document.getElementById('<%=radOption1.ClientID%>').checked = true;
document.getElementById('<%=radOption2.ClientID%>').checked = false;
</script>
I then assign this to a few controls in the code behind and add this to the page load:
protected void Page_Load(object sender, EventArgs e)
{
SetJavascriptAttributes();
}
public void SetJavascriptAttributes()
{
ddl1.Attributes.Add("onFocus", "SetOption1RadioButton()");
ddl1.Attributes.Add("onClick", "SetOption1RadioButton()");
}
Now this works great on the initial load - lovely stuff. When I click on ddl1, the radio button is set accordingly. However, when the update panel posts back, the javascript no longer works.
I'm thinking this is because the html is sent back and the javascript is no longer there.
How do I go about ensuring that, despite an update panel post back occurring, the javascript stays around a little longer and performs as it should?
Any help or suggestions gratefully received.
Since you're using updatepanel's I assume you already have an istance of the ScriptManager on your page. I suggest you use the ScriptManager to register any client scripts, this will insure they get called on partial postbacks:
ScriptManager.RegisterStartupScript();
ScriptManager.RegisterExpandoAttribute();

Categories