bootstrap datepicker in asp.net - asp.net

I am new to coding and trying out bootstrap datepicker in my small project.
I have used bootstrap datepicker in my code. It works fine for selecting a date and populating it on the box but I do not understand how to access this date in codebehind.
here is my code:
<div class="form-group">
<asp:Label ID="lblDOB" runat="server" CssClass="col-xs-12" class="form-control" Text="Date Of Birth" Font-Bold="true"></asp:Label>
<div class="row">
<!-- Include Bootstrap Datepicker -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker.min.css" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker3.min.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.min.js"></script>
<div class="form-group">
<div class="col-xs-12 date">
<div class="input-group input-append date" id="datePicker">
<input type="text" class="form-control" name="date" />
<span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#datePicker')
.datepicker({
format: 'mm/dd/yyyy'
})
.on('changeDate', function(e) {
// Revalidate the date field
$('#eventForm').formValidation('revalidateField', 'date');
});
$('#eventForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
name: {
validators: {
notEmpty: {
message: 'The name is required'
}
}
},
date: {
validators: {
notEmpty: {
message: 'The date is required'
},
date: {
format: 'MM/DD/YYYY',
message: 'The date is not a valid'
}
}
}
}
});
});
</script>
</div>
</div>
<div class="form-group">
<asp:Label ID="lblEmail" runat="server" CssClass="col-xs-12" AssociatedControlID="txtEmail" class="form-control" Text="Email"></asp:Label>
<asp:TextBox ID="txtEmail" runat="server" CssClass="form-control" placeholder="Enter Email"></asp:TextBox>
</div>
<div class="form-group">
<asp:Label ID="lblPhoneNumber" runat="server" CssClass="col-xs-12" AssociatedControlID="txtPhoneNumber" class="form-control" Text="Phone Number"></asp:Label>
<asp:TextBox ID="txtPhoneNumber" runat="server" CssClass="form-control" placeholder="Enter Primary Phone Number"></asp:TextBox>
</div>
<div class="form-group">
<asp:Label ID="lblSecondaryNumber" runat="server" CssClass="col-xs-12" AssociatedControlID="txtSecondaryNumber" class="form-control" Text="Secondary Phone Number"></asp:Label>
<asp:TextBox ID="txtSecondaryNumber" runat="server" CssClass="form-control" placeholder="Enter Secondary Phone Number"></asp:TextBox>
</div>
<div>
<asp:Button ID="btnSubmit" runat="server" CssClass="btn btn-primary btn-lg" Text="submit" />
</div>
CodeBehind:
Protected Sub btnSubmit_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
InitiateAdd()
End Sub
Private Sub InitiateAdd()
Try
Dim conn As New Connection(Connection.EConnectionString.Library)
Using conn.Connection
Actions.AddInformationUser(datepicker.text,txtEmail.Text, txtPhoneNumber.Text, txtSecondaryNumber.Text, conn.Connection)
End Using
Catch ex As Exception
Library.Helper.ShowMessage(ex.Message)
End Try
End Sub
If I want to use the Email in my codebehind then I would use txtEmail.text, but I do not understand how to get the value in datepicker in my codebehind.I tied it with datePicker.text as datePicker was the id given to the div but it did not work.

The datepicker appears to be getting it's values stored in:
<input type="text" class="form-control" name="date" />
Try adding a runat="server" attribute in there and and Id, use that Id in your code to pick it up.

Related

Coudn't pass the form values one page to another asp.net

i have to values values one form to another using asp.net i can pass to another only regno and name only another values cannot pass i got the error missing directive what i tried so far i attached below
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label>Reg No</label>
<asp:TextBox ID="regno" runat="server" class="form-control" required></asp:TextBox>
</div>
<div class="form-group">
<label>Name</label>
<asp:TextBox ID="name" runat="server" class="form-control" required></asp:TextBox>
</div>
<div class="form-group">
<label>Address</label>
<input type="text" id="phone" name="phone" class="form-control" required />
</div>
<div class="form-group">
<label>Gender</label>
<asp:RadioButton ID="RadioButton1" runat="server" OnCheckedChanged="RadioButton1_CheckedChanged" Text="Male" />
<asp:RadioButton ID="RadioButton2" runat="server" Text="FeMale" />
</div>
<div class="form-group">
<label>Interest</label>
<asp:CheckBox ID="CheckBox1" runat="server" Text="Cricket" />
<asp:CheckBox ID="CheckBox2" runat="server" Text="Football" />
<asp:CheckBox ID="CheckBox3" runat="server" Text="Cinima" />
</div>
<div class="form-group">
<asp:Button ID="Button1" runat="server" Text="Submit" class="btn btn-success" OnClick="Button1_Click" />
</div>
</div>
Button Event
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("form2.aspx?regno=" +
this.regno.Text + "&name=" +
this.name.Text + "&phone=" +
this.phone.Text ); this line i got error missing directive
}
Second form
Label1.Text = Request.QueryString["regno"];
Label2.Text = Request.QueryString["name"];
Label3.Text = Request.QueryString["phone"];
phone seems to be ordinary input and not TextBox (note the input tag and lowercase id). Also, you are requesting a txtphone while id=phone.
Be aware, string data should be Url encoded before sending it through querystring.
Edit: replace
<input type="text" id="phone" name="phone" class="form-control" required />
with
<asp:TextBox ID="phone" runat="server" class="form-control" required></asp:TextBox>
Edit: for checkboxes, use something like
var interests = new List<string>();
if (chkCheckBox1.Checked)
interests.Add(chkCheckBox1.Text);
if (chkCheckBox2.Checked)
interests.Add(chkCheckBox2.Text);
if (chkCheckBox3.Checked)
interests.Add(chkCheckBox3.Text);
var interestsString = string.Join(",", interests);
var sex = RadioButton1.Checked ? RadioButton1.Text : RadioButton1.Text;
Response.Redirect("form2.aspx" +
"?regno=" + this.regno.Text +
"&name=" + this.name.Text +
"&phone=" + this.phone.Text +
"&sex=" + HttpUtility.UrlEncode(sex) +
"&interest=" + HttpUtility.UrlEncode(interestsString) +
// if needed, decode with HttpUtility.UrlDecode(Request.QueryString["interest"]:
// var interests = HttpUtility.UrlEncode(interestsString);

asp:Updatepanel, trouble with updatepanels as my pages are doing full postback everytime I click on a button

I am having a simple page which has two steps:
step 1: create a username and password when I click next button it has to go to step 2: to enter all the information.
When I click the next button, the step 2 page loads and immediately goes back to step 1. I tried putting the update panels around entire step 2 but then it doesnt allow me to click previous button or submit button. I also tried surrounding all my labels and textboxes with update panel leaving the previous and submit button but somehow it did not work too. Please help me out.
Also I have a bootstrap date picker included in this. I dont understand how to get the date entered in that box in code behind.
Here is my code:
Default.aspx
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Template/Main.Master" CodeBehind="Default.aspx.vb" Inherits="Library._Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap1-css">
<link rel="stylesheet" runat="server" media="screen" href="/css/StyleSheet.css" type="text/css" />
<link rel="stylesheet" runat="server" media="screen" href="~/css/StyleSheet3.css" type="text/css" />
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<%--<script type="text/javascript" src="/js/JavaScript.js"></script>--%>
<script type="text/javascript" src="/js/JavaScript1.js"></script>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="container">
<div class="row">
<div class="span12">
<div class="" id="loginModal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class="col-xs-12 col-md-6" id="Heading1"> Welcome! </h2>
</div>
<div class="modal-body">
<div class="well">
<ul class="nav nav-tabs">
<li class="active">User Login</li>
<li>Manager Login</li>
<li>Create Account</li>
</ul>
<div id="myTabContent" class="tab-content">
<div class="tab-pane active in" id="Userlogin">
<div class="form-horizontal">
<fieldset>
<asp:UpdatePanel ID="uplogin" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSubmit" EventName="click" />
</Triggers>
<ContentTemplate>
<div class="control-group">
<asp:Label ID="lblUsername" runat="server" CssClass="col-xs-12" Text="UserName"></asp:Label>
<asp:TextBox ID="txtUsername" runat="server" CssClass="form-control"></asp:TextBox>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div class="control-group">
<asp:Label ID="lblPassword" runat="server" CssClass="col-xs-12" Text="Password"></asp:Label>
<asp:TextBox ID="txtPassword" TextMode="Password" CssClass="form-control" runat="server"></asp:TextBox>
</div>
<div class="control-group">
<div class="controls">
<asp:UpdatePanel ID="upLogin2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:button cssclass="btn btn-success btn-block" ID="btnULogin" runat="server" Text="Login"/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</fieldset>
</div>
</div>
<div class="tab-pane fade" id="ManagerLogin">
<div class="form-horizontal">
<fieldset>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSubmit" EventName="click" />
</Triggers>
<ContentTemplate>
<div class="control-group">
<asp:Label ID="lblMUserName" runat="server" CssClass="col-xs-12" Text="UserName"></asp:Label>
<asp:TextBox ID="txtMUserName" runat="server" CssClass="form-control"></asp:TextBox>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div class="control-group">
<asp:Label ID="lblMPassword" runat="server" CssClass="col-xs-12" Text="Password"></asp:Label>
<asp:TextBox ID="txtMPassword" TextMode="Password" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="control-group">
<div class="controls">
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:button cssclass="btn btn-success" ID="btnMLogin" runat="server" Text="Login"/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</fieldset>
</div>
</div>
<div class="tab-pane fade" id="create">
<div class="form-horizontal">
<fieldset>
<div class="container">
<div class="stepwizard col-md-offset-3">
<div class="stepwizard-row setup-panel">
<div class="stepwizard-step">
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="nav-item">
<asp:LinkButton ID="lnkbtnstep1" runat="server" CssClass="nav-link active" href="#step-1" data-toggle="tab" aria-controls="step1" role="tab" title="Step 1" Text="Step 1"></asp:LinkButton>
</li>
<li role="presentation" class="nav-item">
<asp:LinkButton ID="lnkbtnstep2" runat="server" CssClass="nav-link inactive" href="#step-2" data-toggle="tab" aria-controls="step2" role="tab" title="Step 2" Text="Step 2"></asp:LinkButton>
</li>
</ul>
</div>
</div>
</div>
<div role="form">
<div class="row setup-content tab-pane active" id="step-2">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<h3>Create Username and Password</h3>
<asp:UpdatePanel runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="prevBtn" />
</Triggers>
<ContentTemplate>
<div class="form-group">
<asp:Label ID="lblCUsername" runat="server" CssClass="col-xs-12" Text="UserName" class="form-control"></asp:Label>
<asp:TextBox ID="txtCUsername" runat="server" CssClass="form-control" required="required" placeholder="Enter Username"></asp:TextBox>
</div>
<div class="form-group">
<asp:Label ID="lblCPassword" runat="server" CssClass="col-xs-12" Text="Password" class="form-control"></asp:Label>
<asp:TextBox ID="txtCPassword" TextMode="Password" runat="server" CssClass="form-control" required="required" placeholder="Enter Password"></asp:TextBox>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div>
<asp:Button ID="prevBtn" runat="server" CssClass="btn btn-primary prevBtn btn-lg pull-left" Text="Previous" />
<asp:Button ID="btnSubmit" runat="server" CssClass="btn btn-primary btn-lg" Text="submit" />
</div>
</div>
</div>
</div>
</div>
<div class="row setup-content" id="step-1">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<h3>Add Information</h3>
<asp:UpdatePanel runat="server" UpdateMode="conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="nextBtn" />
</Triggers>
<ContentTemplate>
<div class="form-group">
<asp:Label ID="lblFirstName" runat="server" CssClass="col-xs-12" AssociatedControlID="txtFirstName" class="form-control" Text="FirstName"></asp:Label>
<asp:TextBox ID="txtFirstName" runat="server" CssClass="form-control" placeholder="Enter First Name"></asp:TextBox>
</div>
<div class="form-group">
<asp:Label ID="lblLastName" runat="server" CssClass="col-xs-12" AssociatedControlID="txtLastName" class="form-control" Text="LastName"></asp:Label>
<asp:TextBox ID="txtLastName" runat="server" CssClass="form-control" placeholder="Enter Last Name"></asp:TextBox>
</div>
<div class="form-group">
<asp:Label ID="lblAddress" runat="server" CssClass="col-xs-12" AssociatedControlID="txtAddress" class="form-control" Text="Address"></asp:Label>
<asp:TextBox ID="txtAddress" runat="server" CssClass="form-control" placeholder="Enter Address"></asp:TextBox>
</div>
<div class="form-group">
<asp:Label ID="lblDOB" runat="server" CssClass="col-xs-12" class="form-control" Text="Date Of Birth" Font-Bold="true"></asp:Label>
<div class="row">
<!-- Include Bootstrap Datepicker -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker.min.css" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker3.min.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.min.js"></script>
<div class="form-group">
<div class="col-xs-12 date">
<div class="input-group input-append date" id="datePicker">
<input type="text" class="form-control" name="date" />
<span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#datePicker')
.datepicker({
format: 'mm/dd/yyyy'
})
.on('changeDate', function(e) {
// Revalidate the date field
$('#eventForm').formValidation('revalidateField', 'date');
});
$('#eventForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
name: {
validators: {
notEmpty: {
message: 'The name is required'
}
}
},
date: {
validators: {
notEmpty: {
message: 'The date is required'
},
date: {
format: 'MM/DD/YYYY',
message: 'The date is not a valid'
}
}
}
}
});
});
</script>
</div>
</div>
<div class="form-group">
<asp:Label ID="lblEmail" runat="server" CssClass="col-xs-12" AssociatedControlID="txtEmail" class="form-control" Text="Email"></asp:Label>
<asp:TextBox ID="txtEmail" runat="server" CssClass="form-control" placeholder="Enter Email"></asp:TextBox>
</div>
<div class="form-group">
<asp:Label ID="lblPhoneNumber" runat="server" CssClass="col-xs-12" AssociatedControlID="txtPhoneNumber" class="form-control" Text="Phone Number"></asp:Label>
<asp:TextBox ID="txtPhoneNumber" runat="server" CssClass="form-control" placeholder="Enter Primary Phone Number"></asp:TextBox>
</div>
<div class="form-group">
<asp:Label ID="lblSecondaryNumber" runat="server" CssClass="col-xs-12" AssociatedControlID="txtSecondaryNumber" class="form-control" Text="Secondary Phone Number"></asp:Label>
<asp:TextBox ID="txtSecondaryNumber" runat="server" CssClass="form-control" placeholder="Enter Secondary Phone Number"></asp:TextBox>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div>
<asp:Button ID="nextBtn" runat="server" CssClass="btn btn-primary nextBtn btn-lg pull-right" Text="Next" />
</div>
</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Default.aspx.vb
Public Class _Default
Inherits Library.Helper
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
txtUsername.Focus()
End If
End Sub
Protected Sub btnULogin_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnULogin.Click
InitiateULogin()
End Sub
Protected Sub btnMLogin_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMLogin.Click
InitiateMLogin()
End Sub
Protected Sub btnSubmit_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
InitiateCreateUserName()
InitiateAdd()
End Sub
Private Sub InitiateULogin()
Try
Dim conn As New Connection(Connection.EConnectionString.Library)
Using conn.Connection
Actions.ULogin(txtUsername.Text.Trim(), txtPassword.Text.Trim(), "User", conn.Connection)
End Using
Catch ex As Exception
Library.Helper.ShowMessage(ex.Message)
End Try
End Sub
Private Sub InitiateMLogin()
Try
Dim conn As New Connection(Connection.EConnectionString.Library)
Using conn.Connection
Actions.MLogin(txtMUserName.Text.Trim(), txtMPassword.Text.Trim(), "Manager", conn.Connection)
End Using
Catch ex As Exception
Library.Helper.ShowMessage(ex.Message)
End Try
End Sub
Private Sub InitiateCreateUserName()
Try
Dim conn As New Connection(Connection.EConnectionString.Library)
Using conn.Connection
Actions.CreateUserId(txtCUsername.Text, txtCPassword.Text, "User", conn.Connection)
End Using
Catch ex As Exception
Library.Helper.ShowMessage(ex.Message)
End Try
End Sub
End Class

How to wrap ASP.net validation controls in Bootstrap classes?

I am using Bootstrap 3 with ASP.NET webforms and I am completely new to Bootstrap. The webform I am working on uses ASP.net validation controls. My web form has a standard layout with two columns and I am using "form-group" class to group my labels and input fields.
Now the problem is that as I am placing the label, input field as well as its validator in the Bootstrap "form-group" class, the message in the text property of the validator is being displayed in the next line after validation. I want that to be displayed right next to the input field. Is there any alternative way I can do this?
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="txtBox">Address <span class="required">*</span></asp:Label>
<asp:TextBox id="txtBox" runat="server" CssClass="form-control"/>
<asp:RequiredFieldValidator ID="rfvLine1" ValidationGroup="<%# ValidationGroup %>" ControlToValidate="txtBox" runat="server" Display="Dynamic" ErrorMessage="Line 1 is required." Text="*"/>
</div>
Easiest way is to create validation in separate column.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style type="text/css">
.required {
color: #e31937;
font-family: Verdana;
margin: 0 5px;
}
.field-validation-error {
color: #e31937;
font-weight: bold;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<br />
<div class="container form-horizontal">
<div class="form-group">
<asp:Label runat="server"
AssociatedControlID="txtBox"
CssClass="col-xs-12 col-sm-4 control-label">
Address
<span class="required">*</span>
</asp:Label>
<div class="col-xs-12 col-sm-4 ">
<asp:TextBox ID="txtBox" runat="server"
CssClass="form-control" />
</div>
<div class="col-xs-12 col-sm-4 form-control-static">
<asp:RequiredFieldValidator ID="rfvLine1"
ControlToValidate="txtBox" runat="server"
Display="Dynamic"
CssClass="field-validation-error"
Text="Line 1 is required." />
</div>
</div>
<div class="form-group">
<div class="col-xs-12 col-sm-offset-4 col-sm-4 ">
<asp:Button runat="server" ID="SubmitButton"
Text="Submit" CssClass="btn btn-primary" />
</div>
</div>
</div>
</form>
</body>
</html>
Do the following: Updated
<div class="container">
<h4 class="form-signin-heading">Info</h4>
<div class="form-group">
<div class="col-xs-7 col-sm-7">
<asp:TextBox runat="server" placeholder="Garage Name" CssClass="form-control username" ID="txtAddress"></asp:TextBox>
</div>
<div class="col-xs-7 col-sm-5">
<span class="help-inline pull-left">
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txtAddress"
ErrorMessage="Address is a required field."
ForeColor="Red" Display="Dynamic">
</asp:RequiredFieldValidator>
</span>
</div>
</div>
<br />
<br />
<div class="form-group">
<div class="col-xs-7 col-sm-7">
<asp:Button ID="Button1" runat="server" Text="Add" CssClass="btn btn-lg btn-primary btn-block" />
</div>
</div>
</div>
I hope, this is what you expected:
By the way, you didn't put the end tag in the RequiredFieldValidator.
#jQuery for check "require" validation for only submit button#
<script type="text/javascript">
(function () {'use strict';
window.addEventListener('load', function () {
var form = document.getElementById('needs-validation');
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false)
{
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
##Submit button HTML##
<asp:Button ID="Button1" runat="server" Text="Submit" class="btn btn-primary" OnClick="Button1_Click" />
##Non Submit button##
<asp:Button ID="btnSearch" runat="server" class="form-control btn-primary " Width="25%" Text="Find" UseSubmitBehavior="false" OnClick="btnSearch_Click" />

Why is linkbutton OnClick not firing?

This is driving me crackers, it's very basic code, just a very basic three textbox contact form and a linkbutton.
<div class="form-group has-feedback">
<asp:Label ID="lblYourName" AssociatedControlID="txtYourName" CssClass="col-sm-3 control-label" runat="server" Text="Your name"></asp:Label>
<div class="col-sm-6">
<asp:TextBox ID="txtYourName" TextMode="SingleLine" CssClass="form-control" runat="server" placeholder="Your name"></asp:TextBox>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
<asp:Label ID="lblNoName" runat="server" Visible="false" Text="Please enter your name"></asp:Label>
</div>
</div>
<div class="form-group has-feedback">
<asp:Label ID="lblEmail" runat="server" AssociatedControlID="txtEmail" Text="Email" CssClass="col-sm-3 control-label"></asp:Label>
<div class="col-sm-6">
<asp:TextBox ID="txtEmail" CssClass="form-control" runat="server" placeholder="Email" TextMode="Email"></asp:TextBox>
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
<asp:Label ID="lblNoEmail" runat="server" Visible="false" Text="Please enter your email"></asp:Label>
</div>
</div>
<div class="form-group">
<asp:Label ID="lblMessage" AssociatedControlID="txtMessage" CssClass="col-sm-3 control-label" runat="server" Text="Your message"></asp:Label>
<div class="col-sm-6">
<asp:TextBox ID="txtMessage" CssClass="form-control" TextMode="MultiLine" placeholder="Your message" runat="server"></asp:TextBox>
</div>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-6">
<asp:LinkButton ID="lnkSubmit" runat="server" OnClick="lnkSubmit_Click" CssClass="btn standard-hover-effect bg-red btn-lg btn-block">
<span class="text">Contact us <i class="fa fa-arrow-right"></i></span>
</asp:LinkButton>
</div>
</div>
The OnClick of the linkbutton points to this simple MailMessage method where it checks name and email boxes are filled in and then sends an email.
protected void lnkSubmit_Click(object sender, EventArgs e)
{
lblNoName.Visible = false;
lblNoEmail.Visible = false;
if (string.IsNullOrEmpty(txtYourName.Text) || string.IsNullOrEmpty(txtEmail.Text))
{
if (!string.IsNullOrEmpty(txtYourName.Text))
{
lblNoName.Visible = false;
}
else
{
lblNoName.Visible = true;
}
if (!string.IsNullOrEmpty(txtEmail.Text))
{
lblNoEmail.Visible = false;
}
else
{
lblNoEmail.Visible = true;
}
}
else
{
MailMessage mm = new MailMessage(txtEmail.Text, "foo#bar.com");
mm.Subject = "Feedback from website";
mm.Body = "Email from " + txtYourName.Text + "<br /><br />" + txtMessage.Text;
SmtpClient smtp = new SmtpClient();
smtp.Host = "mail.websitelive.net";
smtp.Send(mm);
panContactThanks.Visible = true;
}
}
But when I click the submit button, nothing happens. At all. The OnClick doesn't even fire so the breakpoint in the code behind doesn't even get called. It's as if the OnClick even isn't even in the code and it's just a dummy button. What have I missed out?
Please try CauseValidation="false" in link button.
Like:
<asp:LinkButton ID="lnkSubmit" runat="server" OnClick="lnkSubmit_Click"
CauseValidation="false" CssClass="btn standard-hover-effect bg-red btn-lg btn-block">
Wrap your html inside form tag
<form id="someForm" runat="server">
<!--your html-->
</form>
You are using .net server controls, so you need to wrap them inside form. Don't forget to add runat="server"
http://forums.asp.net/t/1463877.aspx?Does+an+aspx+must+have+a+form+tag+
Probably you forgot to add the isPostBack condition in your Page_load
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Control initialization here
}
}
Take a look at ASP.NET page life cycle: https://msdn.microsoft.com/en-us/library/ms178472.aspx
IsPostBack: https://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback(v=vs.110).aspx

asp.net Do not validate Modal form when hidden

I have a modal form (bootstrap), I am using asp.net RequiredFieldValidtors for data entry validation. This validation should only fire when the modal is visible and the user is entering new values into the modal.
The problem I am having is that the validation triggers when the model form is not shown preventing my main page from accepting new data entry from. My modal is only used to add new values and is not part of the normal workflow on my main page.
I have been stuck on this for two days now and have tried many different things and just can't get it figured out.
Any suggestions on how to handle this while keeping my RequiredFieldValidator rules intact?
Thanks
Edit - Adding modal forms code.
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<div class="modal fade" id="modNewStakeholder" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Add Stakeholder</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label class="control-label">First Name:</label>
<asp:TextBox class="form-control focus" ID="tFirstName" runat="server" AutoComplete="off" placeholder="First name is required"></asp:TextBox>
<asp:RequiredFieldValidator ID="rftFirstName"
runat="server" ErrorMessage="Required Field"
ControlToValidate="tFirstName" Display="Dynamic"
ValidationGroup="ValGroupNewStake"></asp:RequiredFieldValidator>
</div>
<div class="form-group">
<label class="control-label">Last Name:</label>
<asp:TextBox class="form-control" ID="tLastName" runat="server" AutoComplete="off" placeholder="Last name is required"></asp:TextBox>
<asp:RequiredFieldValidator ID="rftLastName"
runat="server" ErrorMessage="Required Field" ControlToValidate="tLastName" Display="Dynamic"
ValidationGroup="ValGroupNewStake"></asp:RequiredFieldValidator>
</div>
<div class="form-group">
<label class="control-label">E-Mail:</label>
<asp:TextBox class="form-control" ID="tEmail" runat="server" AutoComplete="off" placeholder="Email must contain #expeditors.com"></asp:TextBox>
<asp:RequiredFieldValidator ID="rftEmail" runat="server" ControlToValidate="tEmail" Display="Dynamic"
ValidationGroup="ValGroupNewStake"
ErrorMessage="Required Field">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rftEmailAt" runat="server" ControlToValidate="tEmail" Display="Dynamic"
ErrorMessage="Invalid Email, must contain #"
ValidationGroup="ValGroupNewStake"
ValidationExpression="^\w+[\w-\.]*\#\w+((-\w+)|(\w*))\.[a-z]{2,3}$">
</asp:RegularExpressionValidator>
<asp:RegularExpressionValidator ID="rftEmailDomaain" runat="server" ControlToValidate="tEmail" Display="Dynamic"
ErrorMessage="Invalid Email, must be an #abc.com domain"
ValidationGroup="ValGroupNewStake"
ValidationExpression="^.+#[Aa][Bb][Cc][.][Cc][Oo][Mm]$">
</asp:RegularExpressionValidator>
</div>
</div>
<div class="modal-footer">
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-success btn-sm" id="cmdOk_AddSholder" runat="server" onserverclick="cmdOk_AddSholder_ServerClick" ValidationGroup="ValGroupNewStake" causesvalidation="false">Ok</button>
<button type="button" class="btn btn-danger btn-sm" id="cmdCancel_AddSholder" runat="server" data-dismiss="modal" onserverclick="cmdCancel_AddSholder_ServerClick">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="cmdOk_AddSholder" EventName="serverclick" />
</Triggers>
</asp:UpdatePanel>
I've put together a very simplified example of how my application is doing this. The Modal is just an ascx control and does not have an updatepanel. It's actually just a control becoming visible but we use CSS and JavaScript to make it a modal. The same logic should still apply as I've made this sample from a functioning modal.
Modal.ascx
Validators have ValidationGroup and are disabled. Button is also assigned to ValidationGroup:
<div id="approvalModal" style="display: none;">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Enabled="false"
ControlToValidate="TextBox1" ValidationGroup="testValidationgGroup" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="testValidationgGroup" />
</div>
Modal.ascx.vb
Enable the validator in a property:
Partial Class Modal
Inherits System.Web.UI.UserControl
Public WriteOnly Property Enable() As Boolean
Set(value As Boolean)
RequiredFieldValidator1.Enabled = value
End Set
End Property
End Class
PageWithModal.aspx (note: uses jQuery)
<script>
function setupTestModal() {
var modal = $('#approvalModal');
if (modal.css('display') == 'none') {
modal.show();
}
}
</script>
<asp:Button ID="ShowModal" runat="server" Text="Show Modal" OnClick="ShowModal_Click" />
<uc1:Modal runat="server" ID="testModal" />
PageWithModal.aspx.vb
Notice that when you click the ShowModal button, the validation does NOT fire. However, when the modal is visible, the Validator has been enabled.
Protected Sub ShowModal_Click(sender As Object, e As EventArgs)
testModal.Enable = True
Dim script = String.Concat("setupTestModal();")
ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType(), "Popup", script, True)
End Sub

Resources