I know JavaScript and asp.net but this is first time I am using JavaScript in asp.net . I face a little problem.
My problem is JS function isvaliduser() return true or false,all time 'cObj.Save(courseObj)' is called ! I need when JS function return true only that time cObj.Save(courseObj) will call otherwise cObj.Save(courseObj) will not call.
This is my code :
CGateway cObj = new CGateway ();
protected void saveButton_Click(object sender, EventArgs e)
{
CInfo cInfoObj = new CInfo();
cInfoObj.AName= ANameTextBox.Text;
cObj.Save(courseObj);
}
JavaScript :
function isvaliduser()
{
var uid;
var temp = document.getElementById("<%=ANameTextBox.ClientID %>");
uid = temp.value;
if(uid == "")
{
alert ("Please Enter UserName”);
return false;
}
else
{
return true;
}
}
ASPX:
<asp:Button ID="saveButton" runat="server" Text="Save"
OnClientClick ="javascript:isvaliduser()" />
How can I do it? Thank you.
You need the OnClientClick to return true or false (which if true will submit the button and if false will not). Something like this should work:
<asp:Button ID="saveButton"
runat="server"
Text="Save"
OnClientClick="return isvaliduser();" />
Related
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;
I am not getting this Modal window / javascript stuff , I’m a bit of a noob I ve found tons of stuff about this trawling around
But its hard to find the answer when you lack the experience to ask the correct question.
and are not up to speed with all the jargon either
System.windows.froms.messagebox doesn’t work in a web situation.. I’ve discovered that much,,, This is an intranet application
How do I evaluate the result of the javascript function OpenDialogue() in a similar way to declaring DialogResult myVar =
I have a button event handler like this
protected void but_Comds(object sender, EventArgs e)
{
GridViewRow row = results.SelectedRow;
string crn = Convert.ToString(row.Cells[13].Text);
if (sender == but_crn)
{
checkData(row, crn);
}
}
Then some methods
private void checkData(GridViewRow row, string crn)
{
if (stuff)
{
DialogResult checkCrn = System.Windows.Forms.MessageBox.Show("a mesage",
"Data Check",
MessageBoxButtons.YesNoCancel);
if (checkCrn == DialogResult.No)
{
Do stuff;
}
if (checkCrn == DialogResult.Cancel)
{
Do other stuff;
}
}
else
{
Do stuff instead
}
}
I can get the dialogue to run easy enough as a child page but I can’t work out capture the return value from the child page.
I have been trying to wrap it into a method amongst other things
And I can see this doesn’t work because ClientScript.RegisterStartupScript Is void.
protected string MsgDialogue()
{
Return ClientScript.RegisterStartupScript(this.GetType(),
"newWindow", String.Format("<script>OpenDialog();</script>"));
}
I have also tried okClicked(object sender, eventargs e) methods in the childs code behind
And tried to write a variable into the MySession class and then get that variable in the checkData (row, crn) method
There must be some simple more elegant way of doing this without having to trawl thousands of pages
Hoping to stumble on it..
Here is my javascript on the mainpage
<script type="text/javascript">
function OpenDialog() {
// get the control values
var str1 = 'test';
// create an array with the values
var winArgs = new Array(str1);
var winSettings = 'center:yes;resizable:no;help:no;status:no;dialogWidth:250px;dialogHeight:200px';
// return the dialog control values after passing them as a parameter
winArgs = window.showModalDialog('child.aspx', winArgs, winSettings);
// see if the array is null
if (winArgs == null) {
window.alert('no data returned!');
}
return winArgs;
}
</script>
Here is child.aspx
<head runat="server">
<title></title>
<base target="_self"/>
<script type="text/javascript">
function GetData() {
// intialize variables and array to empty
var str1 = '';
var winArgs = new Array(str1);
// get the values as arguments and set the controls
winArgs = window.dialogArguments;
document.getElementById('TextBox1').value = winArgs[0];
}
function but_ok() {
window.returnValue = "ok";
window.close();
}
function but_cancel() {
window.returnValue = "cancel";
window.close();
}
function but_yes() {
window.returnValue = "yes";
window.close();
}
function but_no() {
window.returnValue = "no";
window.close();
}
</script>
</head>
<body onload="GetData()">
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly ="true"></asp:TextBox>
<asp:Button ID="dlg_ok" runat="server" Text=" OK " />
<asp:Button ID="dlg_cancel" runat="server" Text=" Cancel " />
<asp:Button ID="dlg_yes" runat="server" Text=" Yes " />
<asp:Button ID="dlg_no" runat="server" Text=" No " />
</div>
</form>
</body>
</html>
And child.aspx. cs
public class child : System.Web.UI.Page
{
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
protected global::System.Web.UI.WebControls.TextBox TextBox1;
protected global::System.Web.UI.WebControls.Button dlg_ok;
protected global::System.Web.UI.WebControls.Button dlg_cancel;
protected global::System.Web.UI.WebControls.Button dlg_yes;
protected global::System.Web.UI.WebControls.Button dlg_no;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
dlg_ok.Attributes["onclick"] = "javascript:but_ok()";
dlg_cancel.Attributes["onclick"] = "javascript:but_cancel()";
dlg_yes.Attributes["onclick"] = "javascript:but_yes()";
dlg_no.Attributes["onclick"] = "javascript:but_no()";
}
}
}
Sorry ive posted quite a bit of code but hopefully if you can see what I’m trying to do
Then you might be able to better explain what I’m not getting.
Am using the below code to validate and process some other action. In the script, i check the balance amount and pay amount.Pay amount not exceed the balance amount means it return the error message. Then the else part doesn't redirect to my code behind button click event. i can't find it. Please help me to solve this.
if (ddl_selected == "ebal") {
var cust_balance = document.getElementById('<%= lbl_balance.ClientID %>');
var cust_ramount = document.getElementById('<%= lbl_amount.ClientID %>');
if (cust_balance.innerHTML <= cust_ramount .innerHTML) {
alert('Error Alert : You don\'t have enough balance.!.');
return false;
}
else {
return true;
}
}
<asp:ImageButton ID="btn_activate" runat="server" OnClick="btn_pay_Click"
OnClientClick="return valid_details();"
ImageUrl="~/Images/pay.png" />
protected void btn_pay_Click(object sender, ImageClickEventArgs e)
{
//Event not fire
}
Change
OnClientClick="javascript:valid_details();return true;" instead of
OnClientClick="return valid_details();"
Use
OnClientClick="javascript:return valid_details();
instead of
OnClientClick="return valid_details();
I am having an update button on my from on clicking update i would like to prompt the user as Do you want to delimit the record with Yes and No buttons. If the user clicks on Yes i would like to execute the code which can delimit the record if not just update the record.
My sample code
protected void btnUpdate1_Click(object sender, EventArgs e)
{
EmpID = Convert.ToInt32(HiddenField1.Value);
if (ID == 2)
{
oEmployeePersonalData.EmpID = EmpID;
oEmployeePersonalData.PhoneNumberTypeID = ddlPhoneType.SelectedValue;
oEmployeePersonalData.PhoneNumber = Convert.ToInt64(txtph1.Text);
oEmployeePersonalData.EndDate = DateTime.Today.AddDays(-1);
//As per my requirement if i click on yes i would like to execute this code
if (oEmployeePersonalData.PhoneDetailUpdate())
{
}
// If No different code
if(confirm("Would you like to delimit the record"))
{
//Delimit record code or return true;
}
else
{
return false;
}
Add following javascript function in the header of the page
<script type="text/javascript">
function update() {
var result = confirm("Do you want to delimit the record?")
if (result) {
}
else {
return false;
}
}
</script>
and then attach the event to button
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" OnClientClick="return update();"/>
var ans = confirm("Do you want to delimit the record?")
if (ans){
//clicked on yes
}
else{
return false;
}
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>