Run javascript on the first page load - javascript

I only want to run a javascript method on the page load the 1st time only. If there is a postback I do not want to run that method again.
This method is setting the defaults to certain textboxes.
If I add an onLoad to the body element it runs it each time on the postback. I've tried a ClientScript.RegisterStartupScript but that too runs the method on the postback as well.
Am I going to have to do it old school where I have to increment a hidden value and check that each time?

Try defining the method within your Page_Load event using the IsPostBack property to determine if it is the initial load or not :
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// It is the initial load, call your script
ClientScript.RegisterStartupScript(...);
}
}
The Page_Load event will be called every time that your page is loaded, regardless of a PostBack or not. It will only ever be false on the initial load, so if you place your call within there, it should only execute the script a single time.

Related

Need to call a Javascript method from the code-behind

I have my code-behind class and there I have an EventListener, I need to refresh the whole page when my EventListener catches an ´Event´.
How do I do this? I have a JavaScript function in my client-side window.location.reload(true).
The problem is that the javascript never gets executed.
Code-Behind:
private void WebResponse_Msg(object sender, EventArgs e){
ClientScript.RegisterClientScriptBlock(typeof(Page), Guid.NewGuid().ToString(), "refresh();", true);
}
JS:
<script type="text/javascript">
function refresh() {
window.location.reload(true);
}
</script>
Server side code can not trigger javascript (client side code) whenever you want (like when an event is triggered).
However there are several workarounds that I mention 2 of them:
1.Using SignalR
2.Logging that event when triggered in a Session, and checking the session value by ajax periodically.

Call JavaScript function after Telerik RadPageView finishes loading?

I'm using Telerik UI for asp.net. Specifically I'm using RadTabStrip with partial page postbacks to allow the user to tab through different sets of data. When the user clicks a tab, some code executes and loads data just for that tab.
I've figured out how to execute codebehind: I set the OnTabClick property of the RadTabStrip, and then in codebehind I check what tab was clicked.
E.g.
protected void tab_Click(object sender, RadTabStripEventArgs e)
{
if (e.Tab.Text == "Info")
{
populateInfoTab();
}
}
private void populateInfotab()
{
// Do some stuff
}
However, I can't figure out how to execute client side javascript after a specific tab is clicked. What I tried:
Set OnClientTabSelected property, and then add some javascript:
function tab_ClientClick(sender, args)
{
var tab = args.get_tab();
if(tab.get_text() == "Info")
{
alert("Tab Clicked");
}
}
The problem is that I need to set the InnerHtml of some div in the clicked pageview after it is clicked. The div does not exist on page load (that specific RadPageView is hidden) so I cannot set it then. Once the user clicks into the tab, and after the page view loads, I need to be able to update the div's InnerHtml through JavaScript.
How would I go about doing this?
First option - if you do not set the RenderSelectedPageOnly property to true, all page views will be rendered on the initial load and you will be able to use JS to find/modify elements in them.
Second option - just set the content from the server as soon as you load the UC, this will usually make things simpler.
Third option - use client-side events (offered by the native PageRequestManager class or the RadAjaxManager, depending on how you setup your AJAX interactions) to execute when the response is received. The difficulty here is to determine which is the postback you need. Looking for the desired element and only executing logic if it exists is the simplest flag you can opt for.
Fourth option - register a script from the server code that will call your function, something like:
populateInfoTab();
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "someKey", "myDesiredFunction()", true);
where you may want to use the Sys.Application.Load to ensure it is executed later than IScriptControl initialization.

Why is __doPostBack() not firing my bound load events?

Here's the situation: I have a variable number of dynamically created update panels on my page, so I thought I would write one method which handles all of the loading for each one.
My Updatepanel creation looks something like this:
Dim newUpdp As New UpdatePanel
newUpdatep.ChildrenAsTriggers = False
newUpdatep.UpdateMode = UpdatePanelUpdateMode.Conditional
newUpdatep.ID = Guid.NewGuid.ToString
AddHandler newUpdatep.Load, AddressOf updatep_load_method
updatep_Holder.ContentTemplateContainer.Controls.Add(newUpdp)
updatep_Holder.Update()
This creates the update panel and binds its load event to the method "updatep_load_method". This method is called as soon as the Updatepanel is inserted into the holder. The method code is as follows:
Private Sub updp_load_method(sender As UpdatePanel, e As System.EventArgs)
Dim div As New HtmlGenericControl("div")
div.InnerText = Date.Time.Now.ToString
sender.ContentTemplateContainer.Controls.Add(div)
sender.Update()
End Sub
A little later on I want to update the panel, and refresh the time. So I use the javascript __doPostBack method. According to Dave Ward, the __doPostBack method follows the full page postback lifecycle, so I figured the load event of my Update panel would be fired and that "updatep_load_method" would be called by that particular update panel...
Although the partial postback occurs, and other update panel's load events are called, my bound ones aren't. So what's happening here?
You need to recreate dynamic controls during Page_Init and have to use the same Id (so you cannot do a Guid.NewGuid.ToString() while recreating the control).
Otherwise, ASP.Net will not be able to locate your control and populate it with data from ViewState.
Here's a good article that explains more about dynamic controls.
Try implementing the RaisePostBackEvent method in your code:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
//call the RaisePostBack event
base.RaisePostBackEvent(source, eventArgument);
//add whatever code you need to execute on postback here
}

RegisterClientScriptCode not working after a partial post back

The following lines of code are in a user control in a SharePoint website.
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "jquery144", "<script type=\"text/javascript\" src=\"/_layouts/Unicre.Web.RUOnline.Controlos/Scripts/jquery-1.4.4.min.js\"></script>", false);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "javascriptgeral", "<script type=\"text/javascript\" src=\"/_layouts/Unicre.Web.RUOnline.Controlos/Scripts/javascript.js\"></script>", false);
Why doesn't it work? I also can't find the respective script tags in the HTML generated in the response.
The problem has to do with an update panel. After the partial postback, the Javascript stops working. Shouldn't it work with the above code?
(I also tried the RegisterClientScriptInclude method but with the same result.)
This isn't going to work on a partial postback. You need to register the scripts on Page_Load. In the user control, attach to the Load event and call ScriptManager.RegisterClientScriptBlock() from that handler.
After the partial postback, the Javascript stops working
An UpdatePanel partial postback is DOM update of the UpdatePanel <div> contents. This means the previous contents are lost, so the state of inline script contained within that <div> loses its state.
See here for more information:
UpdatePanel does its work on the client through the innerHTML DOM property. A delta is retrieved from the server, finds itself in the existing DOM, disposes of the contents, and then assigns the new content via innerHTML. ... But inline script doesn't work this way. Setting the innerHTML of a DOM element to HTML which contains a script block does not cause that script to execute.
Likewise, calling ScriptManager.RegisterClientScriptBlock() on an UpdatePanel update is not going to act like a page load. You could add the <script> elements directly to the UpdatePanel contents, but it won't execute.
Update
You can call javascript code after a partial postback by adding an endRequest handler to the PageRequestManager:
<script>
function load() {
//register the handler
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
//this handler will execute after a partial postback
function EndRequestHandler(){
//...arbitrary code...
}
window.onload = load;
</script>

RegisterClientScriptBlock ASP.net

I want to execute alert when user clicks LinkButton1.It is not working?
protected void LinkButton1_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "abc", "<script language=javascript>alert(hi)</script>");
}
You mistyped the function name. Change aler to alert. Also, you forgot the delimiters around the string that you are trying to alert.
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "abc", "alert('hi');", true);
use the below
<linkButton runat="server" id="lnk1" OnClientClick="alert('hi');" />
I hope your sample doesn't have a typo, but you are calling "aler" instead of "alert"!
Also, this doesn't define that your button would run this script when the user clicks the link button, it'll be executed when the page gets loaded.
For having such behavior, you need to use the "OnClientClick" control's property, and set there the name of the function - event handler - that would do the alert.
linkButton1.OnClientClick = "myEventHandler";
And define your script in some JavaScript file or by registering a client script block during the pre-render event of your container control or page.

Categories

Resources