clientvalidation in asp.net - c#

I am trying to create a required field validation with a customvalidator. However when the field is empty it still does a postback?
<body>
<form id="Form1" runat="server">
<h3>
CustomValidator ServerValidate Example</h3>
<asp:Label ID="Message" Font-Name="Verdana" Font-Size="10pt" runat="server" />
<p>
<asp:TextBox ID="Text1" runat="server" Text="[Name:required]" />
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="Text1" ClientValidationFunction="ClientValidate"
Display="Static" ErrorMessage="" ForeColor="green" Font-Name="verdana" Font-Size="10pt"
runat="server" />
<p>
<asp:Button ID="Button1" Text="Validate" OnClick="ValidateBtn_OnClick" runat="server" />
</form>
</body>
</html>
<script language="javascript">
function ClientValidate(source, arguments) {
alert(arguments.Value.length);
if (arguments.Value != "[Name:required]" && arguments.Value.length > 0) {
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>

Add ValidateEmptyText="True" to your CustomValidator tag
See here for more details.

You should move your <script> tag containing the ClientValidate function to inside your <html> tags, preferably inside the <body> or <head> tags.

Related

How to make the information in a dropdownlist change

So i want to make a drop down list that displays new information if you select different radio buttons.
And im struggling.For Example if radio button 1 is selected the information in dropbox must change to popcorn and sweets.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
margin-left: 18px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" OnCheckedChanged="RadioButton1_CheckedChanged" Text="Day" />
</div>
<asp:RadioButton ID="RadioButton2" runat="server" Text="Night" />
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Cream Soda</asp:ListItem>
<asp:ListItem>coke</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Name"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" CssClass="auto-style1" Width="139px"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Seat No:"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" Width="140px"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Height="20px" Text="Add Choice" />
<br />
<asp:Label ID="Label3" runat="server"></asp:Label>
</form>
</body>
</html>
You must define autopostback="true" on the RadioButton, and then you need to handle the selected value in the codebehind, and re-fill the drop-down with a new item-list.
Page-Cycle will be like this
Page_Load
RadioButton2_Changed
Page_LoadComplete
So make sure you either set the new content in RadioButton2_Changed, or in Page_LoadComplete. If you try to do it in Page_Load, you'll have the old value of radiobutton, and that will not work well ...
You can try the following steps to show the correspond information when you click the radio button.
First, you need to change your html file into the following:
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" OnCheckedChanged="RadioButton1_CheckedChanged" Text="Day" GroupName="Ra" AutoPostBack="true" />
</div>
<asp:RadioButton ID="RadioButton2" runat="server" Text="Night" OnCheckedChanged="RadioButton2_CheckedChanged" GroupName="Ra" AutoPostBack="true"/>
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Name"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" CssClass="auto-style1" Width="139px"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Seat No:"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" Width="140px"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Height="20px" Text="Add Choice" />
<br />
<asp:Label ID="Label3" runat="server"></asp:Label>
</form>
</body>
Second, you need to call the RadioButton1_CheckedChanged event and RadioButton2_CheckedChanged event to to add the listitem.
ListItem list1 = new ListItem("popcorn");
ListItem list2 = new ListItem("sweets");
ListItem list3 = new ListItem("Cream Soda");
ListItem list4 = new ListItem("coke");
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if(RadioButton1.Checked==true)
{
if (!DropDownList1.Items.Contains(list1) && !DropDownList1.Items.Contains(list2))
{
DropDownList1.Items.Clear();
DropDownList1.Items.Add(list1);
DropDownList1.Items.Add(list2);
}
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked == true)
{
if (!DropDownList1.Items.Contains(list3) && !DropDownList1.Items.Contains(list4))
{
DropDownList1.Items.Clear();
DropDownList1.Items.Add(list3);
DropDownList1.Items.Add(list4);
}
}
}
Result:

put reset button in default for code in user control page

this code in user control.ascx page
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Dates.ascx.cs" Inherits="WebApplication3.Dates" %>
<b>Arivval Date: </b><br /> <br />
<asp:Calendar runat="server" ID="Arivval" ></asp:Calendar><br />
<b>Depart Date: </b> <br /> <br />
<asp:Calendar runat="server" ID="Depart" ></asp:Calendar>
and this code in web form page (default.ascx )
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="HotelReservation.aspx.cs" Inherits="WebApplication3.HotelReservation" %>
<%# Register TagPrefix="dt" TagName="Date" Src="~/Dates.ascx" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
</head>
<body>
<asp:Panel runat="server" ID="ph">
<form id="form1" runat="server">
<asp:ImageButton ImageUrl="~/HotelImageButton.jpg" ID="HOTEL" runat="server" PostBackUrl="~/HotelReservation.aspx" />
<asp:ImageButton ImageUrl="~/CarImageButton.jpg" ID="CAR" runat="server" PostBackUrl="~/CarReservation.aspx" />
<h1 > Hotel Search </h1>
<dt:Date id="d" runat="server" /> <br />
<b>Nights:</b> <asp:TextBox id="num" runat="server" TextMode="Number" />
<br /> <br/>
<b> Room Type:</b> <br /> <br />
<asp:RadioButton id="Superior" runat="server" text="Superior" GroupName="RoomType" /> <br />
<asp:RadioButton id="Twin" runat="server" text="Twin" GroupName="RoomType" /> <br />
<asp:RadioButton id="Triple" runat="server" text="Triple" GroupName="RoomType" /> <br />
<asp:RadioButton id="DeLuxe" runat="server" text="DeLuxe" GroupName="RoomType" /> <br />
<asp:RadioButton id="Studio" runat="server" text="Studio" GroupName="RoomType" /> <br />
<br /> <br />
<asp:Button ID="search" Text="Search" runat="server" />
<asp:Button ID="Reset" Text="Reset" runat="server" style="margin-left: 51px" Width="61px" OnClick="Clear" />
</form>
</asp:Panel>
</body>
</html>
in default.ascx.cs page i want to put reset button for calendar in the user control how to do it
protected void Clear(object sender, EventArgs e)
{
num.Text = "";
Boolean f = false;
Superior.Checked = f;
Twin.Checked = f;
Triple.Checked = f;
DeLuxe.Checked = f;
Studio.Checked = f;
}
I want to put in default.ascx.cs in clear event code to make the 2 calendars in the control page unselected
Create public properties for selected dates in your user control and use them in the host page. Something like this.
<%# Control Language="C#" ClassName="Dates" %>
<script runat="server">
public DateTime ArivvalDate
{
get { return Arivval.SelectedDate; }
set { Arivval.SelectedDate = value; }
}
public DateTime DepartureDate
{
get { return Depart.SelectedDate; }
set { Depart.SelectedDate = value; }
}
</script>
<b>Arivval Date: </b><br /> <br />
<asp:Calendar runat="server" ID="Arivval" ></asp:Calendar><br />
<b>Depart Date: </b> <br /> <br />
<asp:Calendar runat="server" ID="Depart" ></asp:Calendar>
Page:
<!DOCTYPE html>
<%# Page Language="C#" %>
<%# Register Src="~/misc/Dates.ascx" TagPrefix="dt" TagName="Date" %>
<script runat="server">
protected void Clear(object sender, EventArgs e)
{
lstRoomType.SelectedIndex = -1;
d.ArivvalDate = DateTime.MinValue;
d.DepartureDate = DateTime.MinValue;
}
protected void search_Click(object sender, EventArgs e)
{
test.Text = string.Format("Arrival: {0:M/d/yy}, Departure: {1:M/d/yy}, Room Type: {2}", d.ArivvalDate, d.DepartureDate, lstRoomType.SelectedValue);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Reservation Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Hotel Search </h1>
<dt:Date ID="d" runat="server" />
<br />
<b>Nights:</b>
<asp:TextBox ID="num" runat="server" TextMode="Number" />
<br />
<br />
<b>Room Type:</b>
<br />
<br />
<%--use list instead of a set of individual RB --%>
<asp:RadioButtonList runat="server" ID="lstRoomType">
<asp:ListItem Text="Superior" Value="Superior" />
<asp:ListItem Text="Twin" Value="Twin" />
<asp:ListItem Text="Triple" Value="Triple" />
<asp:ListItem Text="Deluxe" Value="Deluxe" />
<asp:ListItem Text="Studio" Value="Studio" />
</asp:RadioButtonList>
<br />
<br />
<asp:Button ID="search" Text="Search" runat="server" OnClick="search_Click" />
<asp:Button ID="Reset" Text="Reset" runat="server" Style="margin-left: 51px" Width="61px" OnClick="Clear" />
<br />
<asp:Literal ID="test" runat="server" />
</div>
</form>
</body>
</html>

LinkButton C# OnClick event not firing within Formview ItemTemplate

I am having an issue with my "save" linkbutton firing and am at a loss. I have included the code for the form and code-behind. I have added some testing to see if the event is firing and it doesn't appear to be so. Any help is appreciated. I am a novice coder so excuse me if there are obvious issues or a better way to proceed. Ultimate goal is to update the entry in the database for the given screen info and then redisplay to updated info.
Again thank you in advance.
UPDATE: I have included the FULL-ish CODE: (removed the sensitive info)
CODEBEHIND:
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class matter : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
...
}
protected void fvdoc_ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
throw new Exception("Clicked");
}
throw new Exception("i've been Clicked");
}
}
PAGE:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="matter.aspx.cs" Inherits="matter" %>
<!DOCTYPE html>
<html>
<head>
<title>Wasatch Client Matter Index</title>
<link rel="shortcut icon" href="~/favicon.ico" type="image/x-icon" />
<meta name="viewport" charset="utf-8" content="width=device-width, initial-scale=1, user-scalable=no"/>
<!-- Latest compiled and minified CSS -->
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Ubuntu+Condensed' type='text/css' />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous" />
<link rel="stylesheet" href="Content/themes/Site.css" />
<!-- Latest compiled JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"/>
</head>
<body>
<div class="navbar">
<div class="row">
<h1 class="col-lg-8 col-lg-offset-2 text-center " style="align-content:center;">Matter Index </h1>
</div>
</div>
<div class="container-fluid">
<form id="form1" runat="server">
<div class="row">
<div class="col-lg-10 col-lg-offset-1 form-group">
<asp:FormView ID="fvdoc" runat="server" DataSourceID="gvdb" OnItemCommand="fvdoc_ItemCommand">
<ItemTemplate>
<h2 class="col-md-12"><asp:Label ID="tbname" runat="server" Text=<%# Bind("docid") %> /> - <asp:Label ID="lbID" runat="server" Text=<%# Bind("sName") %> /></h2>
<div class="left col-md-10">
<legend>Matter Info:</legend>
<div class="form-group"><asp:Label runat="server" Text="Matter" AssociatedControlID="dcname"/>
<asp:TextBox ID="dcname" runat="server" CssClass="form-control" Text=<%# DataBinder.Eval(Container.DataItem,"sDocname") %> Enabled="true"/></div>
</div>
<div class="left col-md-10">
<hr />
<div class="form-group"><asp:Label runat="server" Text="Notes/Comments" AssociatedControlID="dcnotes" />
<asp:TextBox ID="dcnotes" runat="server" Rows="3" TextMode="MultiLine" Text=<%# Bind("sdocdesc") %> Enabled="true"/></div>
</div>
<div class="left col-md-6 col-md-offset-5 txsmall">
<asp:Label runat="server" Text="Filed: " Font-Bold="true" /><asp:Label ID="lblfiledate" runat="server" Text=<%# Bind("dtFiledate") %> CssClass="txsmall" Font-Italic="true" />
<asp:Label runat="server" Text="Modified: " Font-Bold="true" /><asp:Label ID="lblmodify" runat="server" Text=<%# Bind("dtLastModified") + " - " + Bind("susermodified") %> CssClass="txsmall" Font-Italic="true"/>
<asp:Label runat="server" CssClass="txsmall" id="lbltest"/>
</div>
<div class="clear-fix col-md-12">
<div class="form-group">
<asp:LinkButton runat="server" Text="Save" ID="SaveButton" CommandName="Update" CssClass="clear-fix btn btn-primary" />
<asp:LinkButton runat="server" Text="Move" ID="MoveButton" CssClass="clear-fix btn btn-primary" CausesValidation="False" href="m.aspx" />
<asp:LinkButton runat="server" Text="Home" ID="HomeButton" CssClass="clear-fix btn btn-primary" CausesValidation="False" href="default.aspx"/>
</div>
</div>
</ItemTemplate>
</asp:FormView>
</div>
</div>
<hr class="col-lg-10 col-lg-offset-1" />
</form>
</div>
...
</body>
</html>
Your link button is present inside a formview item template as can be seen below and thus you will not get the individual control event (onclick event of linkbutton). Rather you need to handle the FormView.ItemCommand and do your processing like
<asp:FormView ID="fvdoc" runat="server"
DataSourceID="gvdb" onitemcommand="itemCommandClick">
<ItemTemplate>
.......
<asp:LinkButton runat="server" Text="Save" ID="SaveButton" CommandName="Update" .........
In code behind handle this like
void itemCommandClick(Object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
LinkButton button = e.CommandSource as LinkButton;
//Do rest of the processing
}
}
Your FormView is missing the EditItemTemplate, like so:
<asp:FormView ID="fvdoc" runat="server" DataSourceID="gvdb" OnItemCommand="fvdoc_ItemCommand">
<ItemTemplate>
<!--... Use readonly controls like Label etc...-->
<asp:LinkButton runat="server" Text="Save" ID="EditButton" CommandName="Edit" CssClass="clear-fix btn btn-primary" />
</ItemTemplate>
<EditItemTemplate>
<!--... Use editable controls like TextBox etc...-->
<asp:LinkButton runat="server" Text="Save" ID="SaveButton" CommandName="Update" CssClass="clear-fix btn btn-primary" />
</EditItemTemplate>
</asp:FormView>
For the click on the Edit Button, change to Edit mode, then Handle the Save button to save the new values.
See the MSDN docs for more information.

How to Hide error message of a asp custom validator

I am using asp requiredfieldvalidator. I want the required field validator to fire only when a checkbox on my form is checked.
When the checkbox is fired, the validator works as expected and error message shows up but when the checkbox is unchecked the errormessage that showed up stays on the screen. I have tried different options like validator.resetForm(); disabling the validator, hiding the validator but the error message stays on the screen form. Here is the simplified version of my code:
<script src="jquery-1.4.2.min.js"></script>
<!DOCTYPE html>
<script type="text/javascript">
function enableDisableControls(value) {
var enabledSilentPost = $("#<%=chkEnableSilentPost.ClientID%>").attr("checked");
var validatorControl = $("#<%=valApprovalURL.ClientID%>")[0];
ValidatorEnable(validatorControl, enabledSilentPost);
// If the checkbox is false then assume that the
if (!enabledSilentPost) {
validatorControl.enabled = false;
}
}
$(document).ready(function () {
$("#<%=chkEnableSilentPost.ClientID%>").click(function () {
enableDisableControls();
});
enableDisableControls();
});
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:CheckBox ID="chkEnableSilentPost" runat="server" Width="250px" Text="Enable" />
<asp:Label ID="lblApprovalURL" runat="server" Text="URL" CssClass="controllabel" meta:resourcekey="lblApprovalURLResource"></asp:Label>
<asp:TextBox ID="txtApprovalURL" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="valApprovalURL" runat="server" ControlToValidate="txtApprovalURL" ErrorMessage="Please enter Valid Text" Text="*"></asp:RequiredFieldValidator>
<actk:ValidatorCalloutExtender ID="extApprovalURL" TargetControlID="valApprovalURL" runat="server" Enabled="True"></actk:ValidatorCalloutExtender>
</div>
</form>
I am was able to get the validators to react by doing the following. The Validator was pretty simpe, but I had to predict the ID of the Extender in order for it to work:
<script type="text/javascript">
$(function () {
$('#<%=chkEnableSilentPost.ClientID %>').click(function () {
$("#<%=valApprovalURL.ClientID %>").toggle(this.checked);
$("#extApprovalURL_popupTable").toggle(this.checked);
});
});
</script>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" />
<div>
<asp:CheckBox ID="chkEnableSilentPost" runat="server" Width="250px" Text="Enable" />
<asp:Label ID="lblApprovalURL" runat="server" Text="URL" CssClass="controllabel" meta:resourcekey="lblApprovalURLResource"></asp:Label>
<asp:TextBox ID="txtApprovalURL" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="valApprovalURL" runat="server" ControlToValidate="txtApprovalURL" ErrorMessage="Please enter Valid Text" Text="*"></asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="extApprovalURL" TargetControlID="valApprovalURL" runat="server" Enabled="True"></asp:ValidatorCalloutExtender>
</div>
</form>

CheckBox All only works first two times

I put a checkbox 'Check All', and my code only works first all check and all uncheked. After that none of the checked box follows the attribute of the checkbox of 'Check All'
<script type="text/javascript">
$(function () {
$('#chkAll').click(function () {
$('#divChk .chk input:checkbox').attr('checked', function () {
return $('#chkAll').prop('checked');
});
});
});
</script>
<body>
<form id="form1" runat="server">
<div class="bigDiv">
<asp:CheckBox ID="chkAll" runat="server" Text="Check All" /><br />
<div id="divChk">
<asp:CheckBox ID="CheckBox1" runat="server" Text="1" CssClass="chk" /><br />
<asp:CheckBox ID="CheckBox2" runat="server" Text="2" CssClass="chk" /><br />
<asp:CheckBox ID="CheckBox3" runat="server" Text="3" CssClass="chk" /><br />
<asp:CheckBox ID="CheckBox4" runat="server" Text="4" CssClass="chk" /><br />
</div>
</div>
</form>
</body>
Try this and see if this works.
$('#chkAll').change(function () {
$('#divChk input:checkbox').prop('checked',this.checked);
});

Categories

Resources