Change page state with JavaScript, old state gets recalled on postback - c#

Basically we have the "illusion" of an notification message box that exists as .Visible = false in the MasterPage. When it comes time to display a message in the box, we run a method that looks like this:
public static void DisplayNotificationMessage(MasterPage master, string message)
{
if (Master.FindControl("divmsgpanel") != null)
{
master.FindControl("divmsgpanel").Visible = true;
}
if (master.FindControl("divdimmer") != null)
{
master.FindControl("divdimmer").Visible = true;
}
TextBox thetxtbox = (TextBox)master.FindControl("txtboxmsgcontents");
if (thetxtbox != null)
{
thetxtbox.Text = message;
}
}
Basically through our designers awesome CSS voodoo, we end up with what appears to be a floating message box as the rest of the page appears dimmed out. This message box has a "Close" button to dismiss the "popup" and restore the dimmer, returning the site to the "normal" visual state. We accomplish this with JavaScript in the MasterPage:
function HideMessage() {
document.getElementById("<%# divmsgpanel.ClientID %>").style.display = 'none';
document.getElementById("<%# divdimmer.ClientID %>").style.display = 'none';
return false;
}
and the button's declaration in the .aspx page calls this HideMessage() function OnClientClick:
<asp:Button ID="btnmsgcloser" runat="server" Text="Close" style="margin: 5px;"
OnClientClick="return HideMessage()" />
The problem:
All future postbacks cause the MasterPage to "remember" the state of those divs from how they were before the HideMessage() JavaScript was executed. So in other words, every single postback after the initial call of the DisplayNotificationMessage() method causes the page to return to divmsgpanel.Visible = true and divdimmer.Visible = true, creating an endlessly annoying message box that incorrectly pops up on every postback.
The question:
Since we want the Close function to stay client-side JavaScript, how can we "notify" the page to stop reverting to the old state on postback, for just these two divs?

Can you try setting them to Visible = false in Master_Page Load event? It should hide them and reshow them just when you call DisplayNotificationMessage

Related

pop up does not go for post back in asp.net

I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>
Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}

User text input handling using TextBox

I have this control:
I'm trying to create a kind of validation, that whenever the user enters text to the TextBox, the "Add" button will be Enabled, and when the text is "" (null), the "Add" button is disabled.
I dont want to use validators.
here's the code:
protected void addNewCategoryTB_TextChanged(object sender, EventArgs e)
{
if (addNewCategoryTB.Text != "")
addNewCategoryBtn.Enabled = true;
else
addNewCategoryBtn.Enabled = false;
}
The problam is, that when the user enter's text, the "Add" button doesn't changes from disabled to enabled (and vice versa)...
any ideas?
Is it Web Forms? In Web Forms the TextChanged event of the TextBox won't fire by default.
In order to fire the event, you have to set the AutoPostBack property of the TextBox to true.
BUT, this would perform a HTTP post, what is kink of ugly, or you can wrap that in an UpdatePanel
A more elegant option, is to do that using jQuery, to do that in jQuery, you'll need some code like:
$(document).ready(function() {
$("#<%= yourTextBox.ClientID %>").change(function() {
var yourButton = $("#<%= yourButton.ClientID %>")
yourButton.attr('disabled','disabled');
yourButton.keyup(function() {
if($(this).val() != '') {
yourButton.removeAttr('disabled');
}
});
});
});
You'll need to accomplish this with Javascript, since ASP.NET is incapable of performing such client-side modifications. Think about it ... every time you pressed a letter inside the text box, it would have to postback and refresh the page in order to determine if the text box was empty or not. This is one way that ASP.NET differs from Winforms/WPF.
TextChanged events will make postback on server every time. You don't need to increase those request for such task.
You can use jquery to achieve this
var myButton = $("#btnSubmit");
var myInput=$("#name");
myButton.prop("disabled", "disabled");
myInput.change(function () {
if(myInput.val().length > 0) {
myButton.prop("disabled", "");
} else {
myButton.prop("disabled", "disabled");
}
});
JS Fiddle Demo
You just need to take care of elements Id when you are using Server Controls. For that Either you can use ClientID or set property ClientIdMode="Static"

Sometimes imagebutton click event not fired

I have a method that add's an onclick event too an imagebutton.
But sometimes you have to press the button multiple times before the "pop-up" window opens.
Any idea why this happens?
this is my code were I add the event to my imagebutton:
private void AddProjectDetails()
{
ImageButton imgBtn;
HiddenField hfld;
String ProjectNumber;
for (int i = 0; i < GridViewProperties.Rows.Count; i++)
{
hfld = GridViewProperties.Rows[i].FindControl("HiddenProjId") as HiddenField;
imgBtn = GridViewProperties.Rows[i].FindControl("ibtnShowExtra") as ImageButton;
ProjectNumber = hfld.Value;
imgBtn.Attributes.Add("onclick", "window.open('ProjectDetails.aspx?ProjectNumber=" + Server.UrlEncode(ProjectNumber) + "','Graph','height=590,width=600,left=50,top=50,scrollbars=yes'); return true;");
}
}
Try returning false from the javascript. This will prevent postback. Some times the postback can be faster then the windows.open, and in this case I don't think you want it.
Another solution is using an <a href='...' >image</a> instead of the imagebutton
Why are you using return true inside you java-script function.
Do you need postback on your page.
If not use return false.
I will also suggest you to write a javascript function and call it as follows
function OpenPopUp(projectNumber)
{
window.open("ProjectDetails.aspx?ProjectNumber="+ projectNumber
,'Graph','height=590,width=600,left=50,top=50,scrollbars=yes');
return false;
};
and call it inside your c# code
imgBtn.Attributes.Add("onclick", "return OpenPopUp('"+Server.UrlEncode(ProjectNumber)+"');");
Like Stefano and Shekhar said, you must not use return true for LinkButtons, Imagebuttons, unless you want the page post back.
You can also use this way:
<asp:ImageButton ID="ButtonOpenProject" runat="server" ImageUrl="~/Images/OpenProject.png" OnClientClick="return OpenProject('"<%# ProjectNumber %>"');" />
And in your JavaScript script you do something like this:
function OpenProject(ProjectNumber){
window.open('ProjectDetails.aspx?ProjectNumber=' + ProjectNumber + ','Graph','height=590,width=600,left=50,top=50,scrollbars=yes');
return false;
}
Hope this help.

Delete does not ask for confirmation

When Delete button is clicked, the confirmation box should pop up if the selected node has child nodes. Otherwise, it should not do anything.
Right now, when I click on delete, it just deletes without confirming.
Here is the code:
<asp:Button ID="btn_delete" runat="server" Height="32px"
onclick="btn_delete_Click" OnClientClick = "return childnode();"
Text="Delete" Visible="False" />
<script type="text/javascript">
function childnode() {
var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);
if (selectedNode.childNodes.length > 0) {
return confirm("heloo");
}
return false;
}
</script>
You'll need to return false from the function if you don't want the button push to go through in some cases. Currently you are only returning a value from the function when calling confirm.
If one or both of the if conditions fail, add a return false if you don't want the event to bubble up activating the button/sending the form.
Modification of your existing code
function childnode() {
var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
if (treeViewData.selectedNodeID.value != "") {
var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);
if (selectedNode.childNodes.length > 0) {
return confirm("heloo");
}
return false; // don't send form
}
return false; // don't send form
}
Is it still malfunctioning?
Make sure that the logic inside your function is accurate, webbrowsers will often fail silently when trying to get a property of an undefined variable.
In your definition of your button you have written OnClientClick = "return childnode();", try changing this to OnClientClick="return childnode();" and see if that might solve the problem.
See if the event fires at all, OnClientClick="alert(123);".
Your function have return not in all of it's parts. Probably your function exists without confirm. Review your logic and decide what you want to do if one of your if statements not passed.
Change this:
onclick="btn_delete_Click" OnClientClick = "return childnode();"
To this:
onclick="btn_delete_Click;return childnode();"

Get variable & keep changes after postback

This question is related to: Hide div on clientside click
The issue I am having is that after postback event from asp.net happens onClick any clientside changes made reset how can I keep the client side changes I am making.
Second question how can I get a variable from code behind and pass it into my javascript to perform a comparison.
Html:
<div runat="server" id="someDiv1" enableviewstate="true" >
<asp:LinkButton OnClientClick="Show_Hide_Display()"
ID="lbtnDiv1"
runat="server"
CausesValidation="true"
OnClick="lbtn_onClickServer">
</asp:LinkButton>
</div>
<div runat="server" class="tick" id="div2" style="display:none;" enableviewstate="true">
</div>
Javascript:
<script type="text/javascript">
function Show_Hide_Display() {
var div1 = document.getElementById("<%=someDiv1.ClientID%>");
var div2 = document.getElementById("<%=div2.ClientID %>");
if (div1.style.display == "" || div1.style.display == "block") {
div1.style.display = "none";
div2.style.display = "block";
}
else {
div1.style.display = "block";
div2.style.display = "none";
}
}
</script>
The OnClick event causes a postback like it should, on this occassion it checks if users, chosen username is available.
If it is available show a tick, if it isn't error.
I got the error working and am trying to program the tick on client side.
So OnClientClick I am able to toggle between some text and a tick. So I need to:
Get the bool result from code behind
After postback keep tick (if username is available)
I am almost there but can't quite figure the last two points out.
If you are using an UpdatePanel in your page, and assuming that div which you are trying to toggle is outside the control, you can always inject javascript on a partial postback:
Like for e.g. on your button's click event which executes on a partial postback make a call to ScriptManager.RegisterClientScriptBlock() --> How to retain script block on a partial postback?
Alternatively, you can append an end request handler. This is some javascript which should run after the partial postback. --> ASP.NET Register Script After Partial Page Postback (UpdatePanel)
The answer for the both questions lies of checking the boolean value send from the code behind.
1-----.in code-behind c#
protected void Page_Load(object sender, System.EventArgs e)
{
var linkbtn = (Button)Page.FindControl("lbtnDiv1");
linkbtn .Attributes.Add("onClick", "Show_Hide_Display('" + parameter+ "')");
}
2------- change your javascript
function Show_Hide_Display(parameter)
{
if( paramater=='true')
{
----your logic---
}
else
{
----your logic
}
}

Categories

Resources