ASP C# | MessageBox Keeps Displaying - c#

I have a JavaScript MessageBox that keeps displaying when I click events in a Repeater or refresh the current page.
Here is the function:
public myFunctions()
{
}
/** Display Successs/Error Message **/
public void DisplayUserMessage(string messageType, string messageString, Label ErrorMessageLabel)
{
ErrorMessageLabel.Visible = true;
ErrorMessageLabel.Text = "<b>" + messageType.Substring(0, 1).ToUpper() + messageType.Substring(1).ToLower() + ":</b> " + messageString;
ErrorMessageLabel.CssClass = messageType.ToLower() + "_message";
}
public void HideUserMessage(Label ErrorMessageLabel)
{
ErrorMessageLabel.Visible = false;
ErrorMessageLabel.Text = "";
ErrorMessageLabel.CssClass = "";
}
Here is the jquery to make it fade out:
$(document).ready(function () {
/** Success/Error Messages **/
$('.success_message').animate({ opacity: 1.0 }, 2000).fadeOut('slow');
$('.error_message').animate({ opacity: 1.0 }, 2000).fadeOut('slow');
});
Here it is on the MasterPage:
<!-- Message Box -->
<div id="msgBox" runat="server">
<asp:Label ID="ErrorMessageLabel" CssClass="" runat="server" Visible="false"></asp:Label>
</div>
Here is the script in the code-behind when a success occurs:
Label ErrorMessageLabel = (Label)Master.FindControl("ErrorMessageLabel");
new myFunctions().DisplayUserMessage("success", "Administrator Updated!", ErrorMessageLabel);
Anyone know how I can stop it from continually showing up after I click another button or refresh the page?

Use a hidden input and set the value when success function is called. All the other times reset the value. In your document ready function check the value of the hidden element and then call the animate function.
<input id="txtHidSuccess" type="hidden" runat="server" />
In page load
txtHidSuccess.Value = "0";
In the success/error function
txtHidSuccess.Value = "1";
jQuery
$(function(){
if ($("#txtHidSuccess").val() === "1") {
/** Success/Error Messages **/
$('.success_message').animate({ opacity: 1.0 }, 2000).fadeOut('slow');
$('.error_message').animate({ opacity: 1.0 }, 2000).fadeOut('slow');
}
});

I see where you're calling DisplayUserMessage(), but not HideUserMessage(). My guess is that when you set the ErrorMessageLabel properties, they're stored in the View State persisted across postbacks.
Rather than use an ASP.NET Label control, you could try just wrapping some text with a regular div and use CSS to hide it. When the success event occurs in your app, you can use ClientScriptManager.RegisterStartupScript() to write a script to the client that shows the div. Then, your animate functions can fade out the div if it's visible.

if(IsPostBack)
new myFunctions().HideUserMessage(ErrorMessageLabel);
This worked. Thanks #Harie

Related

Access jquery variable from the code behind

This is my html:
<input type="hidden" id="HiddenIndex" name="HiddenIndex" runat="server" />
Some labels and textbox
<asp:Button runat="server" ID="btnGetCoordinates"
Text="Get Coordinates" OnClick="btnGetCoordinates_Click" />
<asp:Label ID="info" runat="server" Text="Waiting...." />
So when the button Get Coordinates is clicked, it will call the Web Services to return some json results from code behind. A Dialog will popup a listbox with these results. It works perfectly until this point. My goal is when a client select an item in the list and click on "Select" button, it will return the selected item's Index, store in a hidden field and manipulate later from the code behind.
This is my jquery function
function ShowPopup()
{
$("#parentForm").fadeTo(500, .2);
$("#C1Dialog1").dialog({
open: function () {
$(".ui-dialog-titlebar-close").hide();
},
buttons: [{
text: "Select",
click: function () {
var value = " ";
storedIndex = " ";
var selected = $("[id*=lstCandidates] option:selected");
selected.each(function () {
value = $(this).val();
storedIndex = $(this).index();
$("#HiddenIndex").val(storedIndex);
});
alert(value + " and index is " + storedIndex); //Show value and index
alert("html hidden value " + $("#HiddenIndex").val()); //show value
$(this).dialog("close");
$("#parentForm").fadeTo(500, 1);
},
style: "margin-right: 40px;"
},
{
text: "Cancel",
click: function () {
$(this).dialog("close");
$("#parentForm").fadeTo(500, 1);
},
style: "margin-left:0px;"
}]
});
}
</script>
As you can see the alert show the value of the hidden field
This is my code behind
protected void btnGetCoordinates_Click(object sender, EventArgs e)
{
//Show the Dialog
if (count > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup();", true);
//never stop here --PROBLEM RIGHT HERE**, there is NO value for Hidden field**
var indexValue = Request.Form["HiddenIndex"];
info.Text = "HiddenIndex is " + indexValue;
}
}
The Info label show nothing when I click on Dialog's select button
Any help would be appreciated , thank you very much.
Probably an issue with the client ID. ASP.NET will not necessarily use the client ID in your markup when emitting the HTML.
There are several ways to fix this, but the easiest is to make the hidden field a plain HTML control. That way ASP.NET won't monkey with it. So change this
<input type="hidden" id="HiddenIndex" name="HiddenIndex" runat="server" />
to this
<input type="hidden" id="HiddenIndex" name="HiddenIndex"/>
Other options:
Set your clientIDmode to static
Modify your jquery selector to use id$='HiddenIndex' so that it ignores any prefix added by ASP.NET.

How to update ASP Web application Literal or Label after user presses button

Warning: I am a novice when it comes to ASP and javascript - I'm more used to desktop apps. Web development is completely new to me.
I have inherited an ASP.net project that I need to keep up-to-date.
My current problem is that I need to display the client time in a text control (label or literal control - doesn't have to specifically be one of those, I just need to show it in text) when the user has clicked a button to 'Save'. If I do it server-side, in the 'SaveChanges' function, I get the time of where the server is.
My button is defined as below:
<asp:Button ID="Save" runat="server" Text="Save Changes" OnClick="SaveChanges"
ValidationGroup="ProjectSummaryValidationGroup"
meta:resourcekey="SaveResource1" />
And my Literal/Label is:
<asp:Label ID="SaveTime" runat="server"></asp:Label>
I have found a javascript function to calculate the client time from one of the other questions on here: (EDIT: I have updated this function so that the text value of my label is being assigned a value)
<script type="text/javascript">
function GetDate(date) {
CurTime = new Date(date);
var offset = (new Date().getTimezoneOffset() / 60) * (-1);
var utc = CurTime.getTime() + (offset * 60000 * (-1));
var serverDate = new Date(utc + (3600000 * offset));
var dateString = (serverDate.getMonth() + 1) + "/" + serverDate.getDate() + "/" +
serverDate.getFullYear() + " " + serverDate.toLocaleTimeString("en-US", { hour12: true });
document.getElementById('<%=SaveTime.ClientID%>').Text = dateString;
}
</script>
My problem is I don't know where to put this javascript function in my apsx page, or how to set the Text value of my label to the date string calculated in the function. I don't even know for sure how to 'call' this function...
So my questions are:
Where do I have to define the javascript function?
How to I 'call' this javascript function when the user clicks the 'Save' button, so that the text one my age is updated?
You can use Java Script Function like
<script type="text/javascript" language="javascript">
function javascriptFunction()
{
}
</script>
call this function
If you Used Update Panels Then You can Use in .Cs Page:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "javascriptFunction();", true);
or On Button's Click in .aspx page
<asp:Button ID="Save" runat="server" Text="Save Changes" OnClick="SaveChanges"
onClientClick="javascriptFunction();"
ValidationGroup="ProjectSummaryValidationGroup"
meta:resourcekey="SaveResource1" />
Other Wise You can Use in .cs page
ClientScript.RegisterStartupScript
(GetType(),Guid.NewGuid().ToString(), "javascriptFunction();",true);
set value of Label in javascript:
document.getElementById('<%=SaveTime.ClientID%>').value = "Your Date";
for label :
void Page_Load(object sender, EventArgs e)
{
lblMyLabel.Attributes.Add("onclick",
"javascript:alert('ALERT ALERT!!!')");
}

How to make textbox visible when previous textbox contains text

I have a WebForm in which i need to place around 30 textboxes mainly to enter barcode scanned data. I am making only the first textbox visible and i want the next textbox to be visible only when the previous textbox is filled with some text. I tried using 'If' condition as well in the textbox on selected change but it doesn't work. Any solutions?
You should use java-script for this because if you will use server side function for this then It will go to server so many times by this your application performance also will decrease.
So create a java-script function that will accept one argument. This argument will take next text box id (text box u want to display).
call this javascript function like this:- onkeyup="calgrid(this,"TextBox2");"
pass nexttextbox id in place of TextBox2...
<script type="text/javascript" language="javascript">
function calgrid(firsttextbox,nexttextbox)
{
var id=firsttextbox.id;
var lastindex= id.lastIndexOf("_");
var strclnt=id.slice(0,lastindex+1);
var txtboxvalue=document.getElementById(firsttextbox).value;
if(txtboxvalue!="")
{
document.getElementById(strclnt+nexttextbox).style.visibility='visible';
}
else
{
document.getElementById(strclnt+nexttextbox).style.display = "none";
}
}
</script>
note:- If you will do visible=false from textbox property then we cannt do visible=true from javascript. So Set style for all textbox style="display:none"
You can resolve your problem by Jquery.
I have make a sample code where i have take four Textbox. Initially only first text box is visible in Web form, when user enter some values in first TextBox next Textbox is automatically display if Previous textbox have a value if not next textbox is not visible.
Sample code is given below :
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
$('input:text:not(:eq(0))').hide()
$('input').on("change paste keyup", function () {
if ($(this).val().length > 0) {
$(this).next().show();
}
else
{
$(this).next().hide();
}
});
I have made sample application for same ,please click on given link for Demo
See Demo application
It's at Client side code so its performance is so fast rather than Server Side.
Please vote me if you feel your problem is resolved by my idea.
I'd name these text boxes similarly like "textbox1", "textbox2", "textbox3" so you can easily find the index of current text box. Then you can use KeyDown event to control what will be shown and what not. This is not a working example but it should give you a good direction.
int currentIndex = 1;
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
TextBox t = Controls["TextBox" + (currentIndex + 1).ToString()] as TextBox;
t.Visible = true;
currentIndex +=1;
}
Use can use Keydown event in your first textbox
try this code
initially set flag=1 as first textbox is going to be by default visible
private void visibleTextBox(Control c)
{
int flag = 1;
foreach (Control c1 in c.Controls)
{
if (c1.GetType() == typeof(TextBox))
{
if (flag == 1)
{
((TextBox)c1).Visible = true;
}
else
{
((TextBox)c1).Visible = false;
}
if (((TextBox)c1).Text != "")
{
flag = 1;
}
else
{
flag = 0;
}
}
}
}
Comparatively simple solution in JavaScript. The code should be somehow like this.
Define onchange event on text boxes like this:
<asp:TextBox ID="txt1" runat="server" onchange="show('txt1', 'txt2');"></asp:TextBox>
<asp:TextBox ID="txt2" runat="server" onchange="show('txt2', 'txt3');" Style="visibility: hidden;"></asp:TextBox>
Then use this JavaScript code to show the next TextBox conditionally. Put this code in the head tag of the page:
<script type="text/javascript">
function show(txtCurrent, txtNext) {
var valueCurrent = document.getElementById(txtCurrent).value;
//alert(valueCurrent);
if (valueCurrent.length > 0) {
document.getElementById(txtNext).style.visibility = 'visible';
}
else {
document.getElementById(txtNext).style.visibility = 'hidden';
}
}
</script>

inline edit control

The label is initialized with the value of the textbox. Upon clicking the label, the textbox is shown. The user can then edit the contents of the textbox. Upon blurring focus, the textbox is hidden and the label shown. Should the user delete the contents of the textbox or only enter whitespace into the textbox, the textbox is not hidden, thus avoiding showing a label with no text. Is there a way to do this ?
Untested, but the general idea should help you out.
HTML:
<asp:TextBox ID="txtA" onblur="txtBlur();" style="display:none;" runat="server"/>
<asp:Label ID="txtA" onclick="txtFocus();" runat="server"/>
Client-side JS:
<script>
var txtA = document.getElementById("<%# txtA.ClientID %>");
var lblA = document.getElementById("<%# lblA.ClientID %>");
function txtBlur()
{
if (txtA.value.trim() != '')
{
lblA.innerText = txtA.value;
lblA.style.display = 'inline';
txtA.style.display = 'none';
}
}
function txtFocus()
{
txtA.value = lblA.innerText;
lblA.style.display = 'none';
txtA.style.display = 'inline';
}
</script>
Check for js validation that textbox is not empty
function Validate()
{
if(document.getElementById("txta").value=="")
{
alert('Please enter the value');
document.getElementById("txta").focus();
return false;
}
}
or you can server side
if (txa.text ="")
{
Response.Write('Text box cannot be empty');
}

ASP.Net double-click problem

having a slight problem with an ASP.net page of mine. If a user were to double click on a "submit" button it will write to the database twice (i.e. carry out the 'onclick' method on the imagebutton twice)
How can I make it so that if a user clicks on the imagebutton, just the imagebutton is disabled?
I've tried:
<asp:ImageButton
runat="server"
ID="VerifyStepContinue"
ImageUrl=image src
ToolTip="Go"
TabIndex="98"
CausesValidation="true"
OnClick="methodName"
OnClientClick="this.disabled = true;" />
But this OnClientClick property completely stops the page from being submitted! Any help?
Sorry, yes, I do have Validation controls... hence the icky problem.
Working on this still, up to this point now:
ASP code:
<asp:TextBox ID="hidToken" runat="server" Visible="False" Enabled="False"></asp:TextBox>
...
<asp:ImageButton runat="server" ID="InputStepContinue" Name="InputStepContinue" ImageUrl="imagesrc" ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="SubmitMethod" OnClientClick="document.getElementById('InputStepContinue').style.visibility='hidden';" />
C# code:
private Random
random = new Random();
protected void Page_Load(object sender, EventArgs e)
{
//Use a Token to make sure it has only been clicked once.
if (Page.IsPostBack)
{
if (double.Parse(hidToken.Text) == ((double)Session["NextToken"]))
{
InputMethod();
}
else
{
// double click
}
}
double next = random.Next();
hidToken.Text = next + "";
Session["NextToken"] = next;
Actually... this nearly works. The double click problem is pretty much fixed (yay!) The image still isn't hidden though.
The general approach is twofold.
Serverside:
On load of the page, generate a token (using System.Random), save it in the session, and write it to a hidden form field
On submit, check that the hidden form field equals the session variable (before setting it again)
Do work
Clientside:
Similar to what you have, but probably just hide the button, and replace it with some text like 'submitting'.
The important thing to note, client side, is that the user may cancel the post by hitting 'escape', so you should consider what to do here (depending on how far along they are the token won't be used, so you'll need to bring the button back from being disabled/hidden).
Complete example follows:
C# (includes code to see it in action):
<html>
<head runat="server">
<title>double-click test</title>
<script language="c#" runat="server">
private Random
random = new Random();
private static int
TEST = 0;
public void Page_Load (object sender, EventArgs ea)
{
SetToken();
}
private void btnTest_Click (object sender, EventArgs ea)
{
if( IsTokenValid() ){
DoWork();
} else {
// double click
ltlResult.Text = "double click!";
}
}
private bool IsTokenValid ()
{
bool result = double.Parse(hidToken.Value) == ((double) Session["NextToken"]);
SetToken();
return result;
}
private void SetToken ()
{
double next = random.Next();
hidToken.Value = next + "";
Session["NextToken"] = next;
}
private void DoWork ()
{
TEST++;
ltlResult.Text = "DoWork(): " + TEST + ".";
}
</script>
</head>
<body>
<script language="javascript">
var last = null;
function f (obj)
{
obj.src = "http://www.gravatar.com/avatar/4659883ec420f39723c3df6ed99971b9?s=32&d=identicon&r=PG";
// Note: Disabling it here produced strange results. More investigation required.
last = obj;
setTimeout("reset()", 1 * 1000);
return true;
}
function reset ()
{
last.src = "http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG";
last.disabled = "false";
}
</script>
<form id="form1" runat="server">
<asp:HiddenField runat="server" ID="hidToken" />
<asp:ImageButton runat="server" ID="btnTest"
OnClientClick="return f(this);"
ImageUrl="http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG" OnClick="btnTest_Click" />
<pre>Result: <asp:Literal runat="server" ID="ltlResult" /></pre>
</form>
</body>
</html>
If you have validation on the page, disabling the button client side gets a little tricky. If validation fails, you don't want to disable the button. Here's a snippet that adds the client side event handler:
private void BuildClickOnceButton(WebControl ctl)
{
System.Text.StringBuilder sbValid = new System.Text.StringBuilder();
sbValid.Append("if (typeof(Page_ClientValidate) == 'function') { ");
sbValid.Append("if (Page_ClientValidate() == false) { return false; }} ");
sbValid.Append(ctl.ClientID + ".value = 'Please wait...';");
sbValid.Append(ctl.ClientID + ".disabled = true;");
// GetPostBackEventReference obtains a reference to a client-side script
// function that causes the server to post back to the page.
sbValid.Append(ClientScript.GetPostBackEventReference(ctl, ""));
sbValid.Append(";");
ctl.Attributes.Add("onclick", sbValid.ToString());
}
See this asp.net thread for more info.
Update: the above code would be used to add the OnClientClick handler in code behind. You could also write the javascript in your aspx markup like so:
<script type="text/javascript">
function disableButton(button)
{
// if there are client validators on the page
if (typeof(Page_ClientValidate) == 'function')
{
// if validation failed return false
// this will cancel the click event
if (Page_ClientValidate() == false)
{
return false;
}
}
// change the button text (does not apply to an ImageButton)
//button.value = "Please wait ...";
// disable the button
button.disabled = true;
// fire postback
__doPostBack(button.id, '');
}
</script>
<asp:ImageButton runat="server" ID="VerifyStepContinue" ImageUrl="button.png"
ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="methodName"
OnClientClick="return disableButton(this);" />
I have solved this by setting a hidden field on the client click before hitting the server.
Then in the server I check the hidden field and if the value is for example something 'FALSE' that might mean I can or cannot of the action.
Similar to Silky's client-side response, I usually make two buttons that look alike except that the second button is disabled and hidden. OnClientClick of the normal button swaps the display styles of the two buttons so that the normal button is hidden and the disabled button is shown.
The double-click feature is a server-side implementation to prevent processing that same request which can be implemented on the client side through JavaScript. The main purpose of the feature is to prevent processing the same request twice. The server-side implementation does this by identifying the repeated request; however, the ideal solution is to prevent this from occurring on the client side.
In the HTML content sent to the client that allows them to submit requests, a small validation JavaScript can be used to check whether the request has already been submitted and if so, prevent the online shopper from submitting the request again. This JavaScript validation function will check the global flag to see if the request has been submitted and, if so; does not resubmit the request. If the double-click feature is disabled on the server, it is highly recommended that the JSP and HTML pages implement this JavaScript prevention.
The following example prevents the form from being submitted more then once by using the onSubmit() action of the form object:
...
<script>
var requestSubmitted = false;
function submitRequest() {
if (!requestSubmitted ) {
requestSubmitted = true;
return true;
}
return false;
}
</script>
...
<FORM method="POST" action="Logon" onSubmit="javascript:submitRequest()">
......
</FORM>
for those who just want to do a quick fix , just hide it and show another button that has no events
<asp:Button ID="RedeemSubmitButton" runat="server" Text="Submit to Redeem" OnClick="RedeemSubmitButton_Click" OnClientClick="hideit();" />
<asp:Button ID="RedeemSubmitButtonDisabled" style="display:none;" runat="server" Text="please wait" OnClientClick="javascript:alert('please wait, processing');" />
<script>
function hideit() {
var btn = $get('<%= this.RedeemSubmitButton.ClientID %>');
var btn2 = $get('<%= this.RedeemSubmitButtonDisabled.ClientID %>');
if (btn != null)
{
btn.style.display = 'none';
btn2.style.display = 'block'
}
}
</script>

Categories