In this snippet we will see how to call a java script client side validation function before server side method execution.
Below code shows calling a onClientClick method before onClick method of button.
onClientClick event is calling a client side validation function where as onClick event is calling server side code. In the validation function we are checking whether the textbox value is empty or not. If the value is empty then it returns false and will not execute any server side code. If the textbox has value then it returns true and server side event(btnSubmit_Click) will be executed.
Designer Page(.aspx)
|
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function
validate() {
//if
validation sucess return true otherwise return false.
if
(document.getElementById("txtSample").value
!= "") {
return
true;
}
alert('Enter
a value');
return
false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter a value:<asp:TextBox ID="txtSample"
runat="server"></asp:TextBox><br />
<asp:Button ID="btnSubmit" runat="server" Text="Click Me" OnClientClick="javascript:return validate();"
OnClick="btnSubmit_Click" />
</div>
</form>
</body>
</html>
|
Code Behind Page(.cs)
|
protected void
btnSubmit_Click(object sender, EventArgs e)
{
Response.Write("The textbox value is " +
txtSample.Text);
}
|
Output:
If textbox value is empty then validation returns false then
alert('Enter a value') comes and server side code will not be executed.
If textbox has value(DotNetMirror) then validation function returns true and
server side code executes. and output is "The textbox value is DotNetMirror".
|
0 Comments:
Post a Comment