How can i determine PostBack value in window.onunload? - c#

In our project we are deleting something after the user left the page. We are using window.unload event for doing this.
window.onunload = function() {
// delete something
}
We are generally using buttons, linkbuttons..etc in UpdatePanel so we hadn't needed to check Page.IsPostBack property.
Today we realized that we used some buttons out of UpdatePanel and this situation had produced some errors. After that we decided to change our method, defined a global variable (var _isPostBack = false), at the top of the our page and:
window.onunload = function() {
if (_isPostBack) {
_isPostBack = false;
return;
}
// delete something
}
Altought i set the g_isPostBack in Page_Load, g_isPostBack didn't change. I tried "RegisterClientScriptBlock", "RegisterOnSubmitStatement" and "RegisterStartupScript" methods. Register methods were called before the onunload event but _isPostBack was set after onunload event had triggered...
if (IsPostBack)
{
Control c = MyClass.GetPostBackControl(this);
bool inUpdatePanel = ControlParentForUpdatePanel(c);
if (!inUpdatePanel)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "_isPostBack = true;", true);
}
}
Is there anyone to help me?

that's the trick...
if you add onsubmit attribute to your form tag:
<form id="form1" onsubmit="return yourPostBack()">
and than write your own function:
function yourPostBack()
{
_isPostBack = true;
return true;
}
and finally in the page load:
if (IsPostBack)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "_isPostBack = false;", true);
}
with this method you can understand that it is postback or not, in window.onunload

I hope i am on the right track here,
As i understand,
the OnUnload() is ClientSide,
and therefore you don't have the server objects
what you can do... is save the value in a hidden field.
As i am used to PHP you can even embed the value in a Javascript variable
Dont know if this applys to ASP.NET:
<script language="javascript">
var MyServerVariable = "<?PHP echo MyServerVariable ?>"
if(MyServerVariable == "Blah...")
{
}
</script>
translates to
<script language="javascript">
var MyServerVariable = "VALUE"
if(MyServerVariable == "Blah...")
{
}
</script>
But same thing can be done with <asp:Label /> , i am sure...

Related

JavaScript Abnormal Behaviour [duplicate]

Is it possible to use the onclientclick property of a button to do a clientside check. If the check returns true, then fire the onclick event. If the clientside check returns false, don't fire the onclick event.
Is that possible?
UPDATE:
These 2 work:
Stops the form from submitting:
OnClientClick="return false;"
Allows the form to submit:
OnClientClick="return true;"
The next 2 do not work:
// in js script tag
function mycheck() {
return false;
}
// in asp:button tag
OnClientClick="return mycheck();"
// in js script tag
function mycheck() {
return true;
}
// in asp:button tag
OnClientClick="return mycheck();"
It submits the form both times.
Why is that?
You want to add return inside OnClientClick after a function is called. Otherwise, the button will post back even if function returns false.
<asp:button ID="Button1" runat="server" OnClick="Button1_Click"
OnClientClick="return checkValidation()" Text="Submit" />
<script type="text/javascript">
function checkValidation() {
return confirm('Everything ok?');
}
</script>
Sure. If you use return false within your OnClientClick it will prevent any navigation from happening. So you're code would look like:
<asp:LinkButton runat="server" OnClientClick="if(!ValidatePage()) { return false;}" />
Yes you can, In onclientClick function call use preventDefault()
function onclientClickFun(e)
{
if(!IsValidationSuccess)
{
e.preventDefault();
}
}
OR
function onclientClickFun(e)
{
if(!IsValidationSuccess)
{
return false;
}
}
In the server page create the button:
var button1 = new Button();
button1.ServerClick += new EventHandler(button1_ServerClick);
button1.OnClientClick = SetJsForSaveBtn();
button1.Attributes.Add("UseSubmitBehavior", "false");
panel.Controls.Add(button1 );
//Contains the server code
private void saveBtn_ServerClick(object sender, EventArgs e)
{
//do something if ClientClick returns true
}
//Contains the JS code for the page
LiteralControl js = new LiteralControl();
panel.Controls.Add(js);
js.Text =#"<script type='text/javascript'>
$(document).ready(function(){
function CheckValidationOnClient(){
if(!ValidatePage()){
return false;
}
else{
return true;
}
};
});
</script> ";
private string SetJsForSaveBtn()
{
var jsfunc = #" return CheckValidationOnClient()";
return jsfunc ;
}
I came across this issue too. Did not like to have to put the OnClientClick=return false on every linkbutton. With a simple page it just easier to use an anchor and avoid asp filling the href in for you.
However this is not always possible. So a Simple conclusion is just to inherit the LinkButton and add a variable like AutoPostBack. if false then just override the output with the html or add the OnClientClick in. I dont really like inline tags.
namespace My.WebControls {
[ToolboxData("<{0}:LinkButton runat=server ID=btn></{0}:LinkButton>"), ParseChildren(true), ToolboxItem(true)]
public class LinkButton : System.Web.UI.WebControls.LinkButton {
private bool _postback = true;
[Bindable(true), Category("Behavior"), DefaultValue(true), Description("Gets or Sets the postback click behavior")]
public bool AutoPostBack { get { return _postback; } set { _postback = value; } }
protected override void Render(System.Web.UI.HtmlTextWriter writer) {
if(!AutoPostBack){
this.OnClientClick = "return false";
}
base.Render(writer);
}
}
}
Many attributes should need to be handled in a ViewState but in this case I think we are good;

RegisterStartUpScript does not fire javascript function

I am calling a JS function from Codebehind, the function is supposed to toggle() or show() a tr in the dom. I am using the following for this purpose:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), DateTime.Now.ToString(), "ToggleTr(1)", true);
If I am in a debugging mode, this works fine magically, but seems to work very spontaneously otherwise. Hence, I used a timeout 500 for this, but I believe that is not a good approach in itself. So my other try was:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), DateTime.Now.ToString(), "window.onload = function() {ToggleTr(1);}", true);
But this does not help either. NOTE: I am using webform aspx pages templated under a MasterPage, So I cannot use the head or a form tag either. This is what I have in my aspx page:
<asp:Panel ID="pnlEmployeeDetails" runat="server">
<script language="javascript" type="text/javascript">
function ToggleTr(showFlag) {
if (showFlag == 1) {
$("#trSupervisor").show();
}
else if (showFlag == 0) {
$("#trSupervisor").hide();
}
}
</script>
Secondly, I am not calling this on PageLoad, the calls vary on several event handlers executed.. What should I do here??

jquery alertbox is getting disabled automatically

I have written the code on
ascx script:
<script src="JScripts/jquery.alerts-1.1/jquery.alerts.js" type="text/javascript"></script>
<script>
$(function() {
$('#ImageButton1').click(function() {
jAlert('Please enter a valid Suggestion ID.', 'Case Entry');
});
});
</script>
and on
Code behind:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "callAlert();", true);
the problem is alert box is automatically getting disabled after some time when page load fully
What could be the reason that the alert box is being disable after clicking on OK button and how to call the callAlert function in proper way.
If you are using Master page or pages then you won't get the Client Id of the button as you are declared it should be declared as $('#<%=ImageButton1.ClientID%>') or $('[id$=ImageButton1]') hope it will solve you problem.
$(document).ready(function(){
$('#<%=ImageButton1.ClientID%>').click(function() {
alert('Please enter a valid Suggestion ID.', 'Case Entry');
});
});
You can try to put the following line before the function
$(document).ready(function() {
This will make it:
$(document).ready(function() {
$('#ImageButton1').click(function() {
jAlert('Please enter a valid Suggestion ID.', 'Case Entry');
});
});
});
If you wait till the page is ready, the alert box won't be overwritten (I hope x)).
Also when you check that text box, check if the condition is false, then give the alert.
Is the condition not false? Build in a check to check if the condition is really true. If so? Redirect.
EDIT:
var answer = Confirm: ("This page will now redirect. Are you ready?")
if (answer)
//redirect
else
return
OK, so first it's important to understand that $(function(){... and $(document).ready(function() {... are equivalent, and nothing inside either will execute until the page is fully loaded. In other words, there's no need to use
Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "callAlert();", true);
That can be removed. Also, I see that you're probably using web forms. Be mindful that the Id attribute that will be rendered is not equal to the Id of the control attribute. In other words, if you have a runat="server" control with an Id of ImageButton1, using the syntax $('#ImageButton1') in your jQuery won't work.
Taking this into account, I've added an example below that uses selectors based on class attributes.
<script type="text/javascript">
$(function () {
$('.ImageButton1').click(function (e) {
var text = $('.TextBox1').val();
var redirect = true;
if (!text) {
redirect = confirm('Empty...are you sure?');
}
if (redirect) {
window.location.href = 'http://your-redirect-here.com';
}
});
});
</script>
<input class="TextBox1" type="text" />
<input class="ImageButton1" type="button" value="Click" />
That should get you where you want to go. Let me know if you have any questions.
var answer = Confirm: ("This page will now redirect. Are you ready?")
if (answer)
{
//redirect
} else
{
return false;
}
Put this after jAlert Box:
return false;
And call the function like this:
return callAlert();

How to detect a postback in frontend (aspx)

I need to detect a postback in the frontend so I can use it with JQuery to change a class on page load. How can I do this?
You can check the IsPostBack property. Eg:
<script type="text/javascript">
$(function()
{
var isPostBack = <%=Page.IsPostBack.ToString().ToLower()%>;
if (isPostBack)
{
alert("Postback");
}
});
</script>
Stolen from this post:
On the server side have this
if(IsPostBack)
{
// NOTE: the following uses an overload of RegisterClientScriptBlock()
// that will surround our string with the needed script tags
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}
On client side this
if(isPostBack) {
// do your thing
}
I put this variable inside the header tag of my asp.net web forms page.
<script type="text/javascript">
var isPostBack = ("true"==="<%= Page.IsPostBack ? "true" : "false" %>");
</script>
The var contains a Boolean. The comparison can probably be shortened.
Simple:
if you're using jquery it has to go after(jquery goes nuts otherwise):
$(document).ready(function(){
});
var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
Then
function whatever(){
if (isPostBack){
//Whatever you want to do
}else{
//Whatever else you want to do
}
}
I'm actually using it with jquery to show a web service status box then force a postback to refresh a ListView, so when it posts back it doesn't invoke the web service or show the status box just the updated ListView data.
$("a[href^='javascript:__doPostBack']").click(function () {
// do something
});

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

I am having what I believe should be a fairly simple problem, but for the life of me I cannot see my problem. The problem is related to ScriptManager.RegisterStartupScript, something I have used many times before.
The scenario I have is that I have a custom web control that has been inserted into a page. The control (and one or two others) are nested inside an UpdatePanel. They are inserted onto the page onto a PlaceHolder:
<asp:UpdatePanel ID="pnlAjax" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="placeholder" runat="server">
</asp:PlaceHolder>
...
protected override void OnInit(EventArgs e){
placeholder.Controls.Add(Factory.CreateControl());
base.OnInit(e);
}
This is the only update panel on the page.
The control requires some initial javascript be run for it to work correctly. The control calls:
ScriptManager.RegisterStartupScript(this, GetType(),
Guid.NewGuid().ToString(), script, true);
and I have also tried:
ScriptManager.RegisterStartupScript(Page, Page.GetType(),
Guid.NewGuid().ToString(), script, true);
The problem is that the script runs correctly when the page is first displayed, but does not re-run after a partial postback. I have tried the following:
Calling RegisterStartupScript from CreateChildControls
Calling RegisterStartupScript from OnLoad / OnPreRender
Using different combinations of parameters for the first two parameters (in the example above the Control is Page and Type is GetType(), but I have tried using the control itself, etc).
I have tried using persistent and new ids (not that I believe this should have a major impact either way).
I have used a few breakpoints and so have verified that the Register line is being called correctly.
The only thing I have not tried is using the UpdatePanel itself as the Control and Type, as I do not believe the control should be aware of the update panel (and in any case there does not seem to be a good way of getting the update panel?).
Can anyone see what I might be doing wrong in the above?
Thanks :)
Well, to answer the query above - it does appear as if the placeholder somehow messes up the ScriptManager.RegisterStartupScript.
When I pull the control out of the placeholder and code it directly onto the page the Register script works correctly (I am also using the control itself as a parameter).
ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), script, true);
Can anyone throw any light on why an injected control onto a PlaceHolder would prevent the ScriptManager from correctly registering the script? I am guessing this might have something to do with the lifecycle of dynamic controls, but would appreciate (for my own knowledge) if there is a correct process for the above.
I had an issue using this in a user control (in a page this worked fine); the Button1 is inside an updatepanel, and the scriptmanager is on the usercontrol.
protected void Button1_Click(object sender, EventArgs e)
{
string scriptstring = "alert('Welcome');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscript", scriptstring, true);
}
Now it seems you have to be careful with the first two arguments, they need to reference your page, not your control
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", scriptstring, true);
I think you should indeed be using the Control overload of the RegisterStartupScript.
I've tried the following code in a server control:
[ToolboxData("<{0}:AlertControl runat=server></{0}:AlertControl>")]
public class AlertControl : Control{
protected override void OnInit(EventArgs e){
base.OnInit(e);
string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
Then in my page I have:
protected override void OnInit(EventArgs e){
base.OnInit(e);
Placeholder1.Controls.Add(new AlertControl());
}
Where Placeholder1 is a placeholder in an update panel. The placeholder has a couple of other controls on in it, including buttons.
This behaved exactly as you would expect, I got an alert saying "Hello" every time I loaded the page or caused the update panel to update.
The other thing you could look at is to hook into some of the page lifecycle events that are fired during an update panel request:
Sys.WebForms.PageRequestManager.getInstance()
.add_endRequest(EndRequestHandler);
The PageRequestManager endRequestHandler event fires every time an update panel completes its update - this would allow you to call a method to set up your control.
My only other questions are:
What is your script actually doing?
Presumably you can see the script in the HTML at the bottom of the page (just before the closing </form> tag)?
Have you tried putting a few "alert("Here");" calls in your startup script to see if it's being called correctly?
Have you tried Firefox and Firebug - is that reporting any script errors?
When you call ScriptManager.RegisterStartupScript, the "Control" parameter must be a control that is within an UpdatePanel that will be updated. You need to change it to:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);
The solution is to put the scripts in an outside js file (lets called 'yourDynamic.js') and re-register de file everytime you refresh the updatepanel.
I use this in the updatepanel_prerender event:
ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "UpdatePanel1_PreRender", _
"<script type='text/javascript' id='UpdatePanel1_PreRender'>" & _
"include('yourDynamic.js');" & _
"removeDuplicatedScript('UpdatePanel1_PreRender');</script>" _
, False)
In the page or in some other include you will need this javascript:
// Include a javascript file inside another one.
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('src'))
{
if(scripts[x].getAttribute('src').indexOf(filename) != -1)
{
head.removeChild(scripts[x]);
break;
}
}
}
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
// Removes duplicated scripts.
function removeDuplicatedScript(id)
{
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('id'))
{
if(scripts[x].getAttribute('id').indexOf(id) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
clearAjaxNetJunk();
}
// Evoids the update panel auto generated scripts to grow to inifity. X-(
function clearAjaxNetJunk()
{
var knowJunk = 'Sys.Application.add_init(function() {';
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].textContent)
{
if(scripts[x].textContent.indexOf(knowJunk) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
}
Pretty cool, ah...jejeje
This part of what i posted some time ago here.
Hope this help... :)
I had an issue with Page.ClientScript.RegisterStartUpScript - I wasn't using an update panel, but the control was cached. This meant that I had to insert the script into a Literal (or could use a PlaceHolder) so when rendered from the cache the script is included.
A similar solution might work for you.
DO NOT Use GUID For Key
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel)
Guid.NewGuid().ToString(), myScript, true);
and if you want to do that , call Something Like this function
public static string GetGuidClear(string x)
{
return x.Replace("-", "").Replace("0", "").Replace("1", "")
.Replace("2", "").Replace("3", "").Replace("4", "")
.Replace("5", "").Replace("6", "").Replace("7", "")
.Replace("8", "").Replace("9", "");
}
What worked for me, is registering it on the Page while specifying the type as that of the UpdatePanel, like so:
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel) Guid.NewGuid().ToString(), myScript, true);
Sometimes it doesnt fire when the script has some syntax error, make sure the script and javascript syntax is correct.
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(),script, true );
The "true" param value at the end of the ScriptManager.RegisterStartupScript will add a JavaScript tag inside your page:
<script language='javascript' defer='defer'>your script</script >
If the value will be "false" it will inject only the script witout the --script-- tag.
I try many things and finally found that the last parameter must be false and you must add <SCRIPT> tag to the java script :
string script = "< SCRIPT >alert('hello!');< /SCRIPT>";
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), key, script, **false**);

Categories