In my whole project I have several events and surprising thing is that sometime some event fire up and sometime doesnot.I don't know hat is going on. I have tried many option after seraching from google. Please someone help me. I am in very bad situation.
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (Session["userid"] != null)
{
if (FileUpload1.HasFile)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath(".")
+ "//images//" + str);
string path = "~//images//" + str.ToString();
con.Open();
Label1.Text = "File uploaded successfully";
main addinfo = new main();
string Id = Request.QueryString["id"];
string SQL = "insert into
mandir(with_user,name,place,with_district,with_religion,
with_religion_category,description,photo)
values('" + Session["userid"] + "','" + txttemplename.Text.Trim()
+ "','" + txtaddress.Text.Trim() + "','" +
ddldistrict.SelectedItem.Value + "','" +
ddlreligion.SelectedItem.Value + "','" +
ddlreligioncategory.SelectedItem.Value +
"','" + txtdescription.Value + "','" + path + "')";
addinfo.saveData(SQL);
con.Close();
txttemplename.Text = "";
txtaddress.Text = "";
txtdescription.Value = "";
string message1 = "Thank you for providing the information";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"Popup", "ShowPopup('" + message1 + "');", true);
// lblenquirymsg.Text = "";
}
else
{
Label1.Text = "File not uploaded successfully";
}
}
else
{
// lblinfo.Text = "You Must Login Or Register To give information";
string message = "You Must Login Or Register To Comment";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"Popup", "ShowPopup('" + message + "');", true);
}
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
<div class="weltext">
<h2>Add information</h2>
<div>
<div class="txt-st4" style="margin-bottom:8px; margin-top:10px;">Please fill the form below to provide information.</div>
<div style="padding:0px 0 10px 0;">
<form method="post">
<div style="margin-bottom:3px;"></div>
<div style="margin-bottom:7px;">
<div style="margin-bottom:3px;">Temple Name <span style="color:#F00">*<br />
</span><asp:TextBox ID="txttemplename" class="input_field1 verifyText" runat="server" style="margin-left: 0px" ></asp:TextBox>
</div>
<%-- <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="please input alphabets." ControlToValidate="txtfullname"
ValidationExpression="^[a-zA-Z]+$" Height="19px" Width="165px"></asp:RegularExpressionValidator>--%>
<asp:RequiredFieldValidator ID="rfvtemplelname" runat="server"
ControlToValidate="txttemplename" ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revtemplelname" runat="server"
ControlToValidate="txttemplename" ErrorMessage="Only alphabets are allowed"
ForeColor="Red" ValidationExpression="^[a-zA-Z ]+$" > </asp:RegularExpressionValidator>
</div>
<div style="margin-bottom:4px;">
<div class="field required">
<div style="margin-bottom:3px;">
Address<span style="color:#F00">*<br /></span>
<asp:TextBox ID="txtaddress" class="input_field1 verifyText" runat="server" style="margin-left: 0px" ></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvaddress" runat="server"
ControlToValidate="txtaddress" ErrorMessage="Please enter valid address"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revaddress" runat="server"
ControlToValidate="txtaddress" ErrorMessage="Only alphabets are allowed"
ForeColor="Red" ValidationExpression="^[a-zA-Z ]+$" > </asp:RegularExpressionValidator>
</div>
</div>
</div>
<div style="margin-bottom:4px;">
<div class="field required">
<div style="margin-bottom:3px;"> Choose district <span style="color:#F00">*<br />
</span><asp:DropDownList ID="ddldistrict" runat="server" class="input_field1 verifyText" OnLoad="ddldistrict_Load" style="margin-left: 0px"></asp:DropDownList></div><div style="margin-bottom:4px;">
<div class="field required">
<br />
</div></div>
<div style="margin-bottom:3px;"> Choose religion<span style="color:#F00">*<br />
</span><asp:DropDownList ID="ddlreligion" class="input_field1 verifyText" runat="server" OnLoad="ddlreligion_Load" style="margin-left: 0px"></asp:DropDownList></div><div style="margin-bottom:4px;">
<div class="field required">
<br />
</div></div>
<div style="margin-bottom:3px;"> Choose religion category <span style="color:#F00">*<br />
</span><asp:DropDownList ID="ddlreligioncategory" class="input_field1 verifyText" runat="server" OnLoad="ddlreligioncategory_Load" style="margin-left: 0px" ></asp:DropDownList>
</div><div style="margin-bottom:4px;">
<div class="field required">
<br />
</div></div>
<%--<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ErrorMessage="please input alphabets." ControlToValidate="txtaddress"
ValidationExpression="^[a-zA-Z]+$" Height="19px" Width="165px"></asp:RegularExpressionValidator>--%>
</div>
</div>
<div style="margin-bottom:3px;">Description<span style="color:#F00">*</span></div>
<div style="margin-bottom:4px;">
<div class="field required">
<textarea id="txtdescription" runat="server" name="description" class="text_area" style="width: 532px; height: 180px"></textarea>
<%-- <asp:RequiredFieldValidator ID="rfvdescription" runat="server" ControlToValidate="txtdescription"
ErrorMessage="*" InitialValue="Select"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revdescription" Runat="server"
ErrorMessage="ERROR: Please enter a valid description<br/>" SetFocusOnError="true" Display="Dynamic"
ControlToValidate="txtdescription" ValidationGroup="MandatoryContent"
ValidationExpression="^[A-Za-z'\-\p{L}\p{Zs}\p{Lu}\p{Ll}\']+$"
ForeColor="Red"></asp:RegularExpressionValidator>--%>
</div>
</div>
Choose picture:<br />
<asp:FileUpload ID="FileUpload1" runat="server" style="margin-left: 0px" /><br />
<%-- <asp:Button ID="Button1" runat="server" Text="Upload Image" onclick="Button1_Click" /><br >--%>
<br />
<span style="color:#F00">
<asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
<span style="color:#F00">
<div id="dialog" style="display: none">
</div>
<asp:Button id="btnSubmit" Text="Submit " runat="server" class="btn" OnClick="btnSubmit_Click" />
<%--<asp:Button ID="btnSubmit" Text="Submit" runat="server" value="Submit Now" class="btn" CausesValidation="False" style="margin-left: 13px" OnClick="btnSubmit_Click" />--%>
<br />
</span>
</span>
<br />
<div>
<%-- <asp:Button ID="btnReset" Text="Reset Form" runat="server" value="Reset Form" class="btn" OnClick="btnReset_Click" />--%>
<asp:Label ID="lblenquirymsg" runat="server"></asp:Label>
</div>
</form>
</div>
</div>
<p>
<asp:Label ID="lblenquirymsg1" runat="server"></asp:Label>
</p>
The above event is also not firing.
Related
The AsyncFileUpload works. Only issue is the file name disappears when the LinkButton to repeat the AsyncFileUpload control is pressed. Is there a way to get and store the file name? FileName does not work. Not really keen on sharing code-behind but may do so if it is necessary to solve this issue.
<asp:UpdatePanel ID="LibraryResourceUpdatePanel" runat="server">
<ContentTemplate>
<div class="field-group list-of-resource">
<asp:Repeater ID="RptRequest" runat="server" OnItemDataBound="RptRequest_ItemDataBound">
<ItemTemplate>
<div class="resource">
<div class="remove-input">
<asp:LinkButton ID="LbRemoveRequest" CssClass="ic fa fa-minus-circle" runat="server" OnClick="LbRemoveRequest_Click" CausesValidation="false"></asp:LinkButton>
<span>Remove</span>
</div>
<h2>Details of Resources
<span class="counter">
<asp:Literal ID="LitCount" runat="server"></asp:Literal>
</span>
</h2>
<ul>
<li>
<fieldset class="form-group">
<legend>Accession No.</legend>
<asp:TextBox ID="TxbAccessionNumber" CssClass="form-control" runat="server" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TxbAccessionNumber" ErrorMessage="Email is required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
<li>
<fieldset class="form-group">
<legend>Details</legend>
<asp:TextBox ID="TxbDetails" runat="server" Rows="4" TextMode="MultiLine" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TxbDetails" ErrorMessage="Details are required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
<li>
<fieldset class="form-group">
<legend>Image</legend>
<ajaxToolkit:AsyncFileUpload runat="server"
ID="FileUpload" OnUploadedComplete="FileUpload_UploadedComplete" ClientIDMode="AutoID" PersistFile="true"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="FileUpload" ErrorMessage="File Upload required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div class="add-input">
<asp:LinkButton ID="LbAddRequest" CssClass="ic fa fa-plus-circle" runat="server" OnClick="LbAddRequest_Click" CausesValidation="false" ></asp:LinkButton>
<span>Add another request</span>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="LbAddRequest" EventName="click" />
</Triggers>
</asp:UpdatePanel>
First add command name to linkbutton and remove click event:
<asp:LinkButton ID="LbAddRequest" runat="server"
CommandName="AddRequest"></asp:LinkButton>
<span>Add another request</span>
And try this ItemCommand event in code-behind to get in work:
protected void RptRequest_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "AddRequest")
{
FileUpload myFileUpload = (FileUpload)e.Item.FindControl("FileUpload");
if (myFileUpload.HasFile)
{
try
{
string filename = Path.GetFileName(myFileUpload.FileName);
myFileUpload.SaveAs(Server.MapPath("~/") + filename);
myStatusLabel.Text = "Upload Success";
}
catch (Exception ex)
{
myStatusLabel.Text = "Upload Fail" + ex.Message;
}
}
else
{
myStatusLabel.Text = "myFileUpload Has No File";
}
}
}
Read detail here : https://forums.asp.net/t/1904302.aspx?FileUpload+Inside+a+Repeater+Can+t+Find+File
I set my textBox Text property with data loaded from the Database. Later the User enter a new value and click on Save to update this info into the database. My problem is that the textBox.Text never change its value.
My TextBox
<asp:TextBox ID="firstNameModal" runat="server" Width="300px" />
When I load the data:
private void loadMyAccount(int id)
{
var query = (from u in db.Users
where u.Id == id
select u).FirstOrDefault();
// Modal data
firstNameModal.Text = query.FirstName;
}
My save button call the method to update the FirstName value:
protected void saveProfile_Click(object sender, EventArgs e)
{
try
{
int id = (int)HttpContext.Current.Session["userId"];
var query = (from u in db.Users
where u.Id == id
select u).FirstOrDefault();
query.FirstName = firstNameModal.Text;
db.SaveChanges();
} catch(Exception ex)
{
Console.Write(ex.ToString());
}
}
I'm new in webforms, but what am I doing wrong?
Here is my form:
<form id="form1" runat="server">
<uc:Header ID="homeHeader" runat="server" />
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 col-xs-offset-0 col-sm-offset-0 col-md-offset-3 col-lg-offset-3 toppad" >
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title"><asp:Label ID="UserName" runat="server"/></h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3 col-lg-3 " align="center"> <img alt="User Pic" src="../img/myAccount.png" class="img-circle img-responsive" /> </div>
<div class=" col-md-9 col-lg-9 ">
<table class="table table-user-information">
<tbody>
<tr>
<td>Full Name:</td>
<td><asp:Label ID="fullName" runat="server" /></td>
</tr>
<tr>
<td>Date of Birth</td>
<td><asp:Label ID="dob" runat="server" /></td>
</tr>
<tr>
<td>Gender</td>
<td><asp:Label ID="gender" runat="server" /></td>
</tr>
<tr>
<td>Phone</td>
<td><asp:Label ID="phone" runat="server" /></td>
</tr>
<tr>
<td>Home Address</td>
<td><asp:Label ID="homeAddress" runat="server" /></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="panel-footer">
<asp:Button ID="editProfile" runat="server" CssClass="btn btn-primary" Text="Edit Profile" OnClientClick="$('#editProfileModal').modal(); return false;" />
<asp:Button ID="myBooks" runat="server" CssClass="btn btn-primary" Text="View my books" OnClick="myBooks_Click" />
</div>
</div>
</div>
<!--- Modal Edit Profile --->
<div class="modal fade" id="editProfileModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" data-dismiss="modal" class="close" type="button">X</button>
<h4 class="modal-title"><strong><asp:Label ID="modalFullName" runat="server" /></strong></h4>
</div>
<div class="modal-body">
<div class="alert alert-info fade in">
<asp:Label runat="server" Text="First Name:" Width="90px" />
<asp:TextBox ID="firstNameModal" runat="server" Width="300px" /> <br /> <br />
<asp:Label runat="server" Text="Last Name:" Width="90px" />
<asp:TextBox ID="lastNameModal" runat="server" Width="300px" /> <br /> <br />
<asp:Label runat="server" Text="Date of Birth:" Width="90px" />
<asp:TextBox ID="dobModal" runat="server" Width="300px" /> <br /> <br />
<asp:Label runat="server" Text="Gender:" Width="90px" />
<asp:TextBox ID="genderModal" runat="server" Width="300px" /> <br /> <br />
<asp:Label runat="server" Text="Phone:" Width="90px" />
<asp:TextBox ID="phoneModal" runat="server" Width="300px" /> <br /> <br />
<asp:Label runat="server" Text="Address:" Width="90px" />
<asp:TextBox ID="homeAddressModal" runat="server" Width="300px" /> <br /> <br />
</div>
</div>
<div class="modal-footer">
<asp:Button ID="saveProfile" OnClick="saveProfile_Click" runat="server"
CssClass="btn btn-primary" Text="Save" />
<button data-dismiss="modal" class="btn btn-default" type="button">Close</button>
</div>
</div>
</div>
</div>
</form>
Code behind:
public partial class Views_MyAccount : System.Web.UI.Page
{
LibraryEntities db = new LibraryEntities();
protected void Page_Load(object sender, EventArgs e)
{
if(HttpContext.Current.Session["userId"].Equals(0))
{
Response.Redirect("Login.aspx");
}
else
{
loadMyAccount((int) HttpContext.Current.Session["userId"]);
}
}
private void loadMyAccount(int id)
{
var query = (from u in db.Users
where u.Id == id
select u).FirstOrDefault();
UserName.Text = query.FirstName + " " + query.LastName;
fullName.Text = query.FirstName + query.LastName;
DateTime dt = (DateTime) query.Dob;
dob.Text = dt.ToString("MM/dd/yyyy");
gender.Text = (query.Gender == false ? "Female" : "Male");
phone.Text = query.Phone;
homeAddress.Text = query.Address;
// Modal data
modalFullName.Text = query.FirstName + " " + query.LastName;
firstNameModal.Text = query.FirstName;
lastNameModal.Text = query.LastName;
dobModal.Text = dt.ToString("MM/dd/yyyy");
genderModal.Text = (query.Gender == false ? "Female" : "Male");
phoneModal.Text = query.Phone;
homeAddressModal.Text = query.Address;
}
protected void myBooks_Click(object sender, EventArgs e)
{
}
protected void saveProfile_Click(object sender, EventArgs e)
{
try
{
int id = (int)HttpContext.Current.Session["userId"];
var query = (from u in db.Users
where u.Id == id
select u).FirstOrDefault();
query.FirstName = firstNameModal.Text;
db.SaveChanges();
} catch(Exception ex)
{
Console.Write(ex.ToString());
}
}
}
Double check that the text box and the save profile button are in the same <form runat="server"> HTML tag. Usually this is the case when the page is using a site.master file.
After that, try to check the value of the textbox in the different events of the page life cycle using the debugger.
EDIT:
I think you need to wrap the loadMyAccount method in a IsPostBack conditional, something like this:
protected void Page_Load(object sender, EventArgs e)
{
if(HttpContext.Current.Session["userId"].Equals(0))
{
Response.Redirect("Login.aspx");
}
else
{
if(!IsPostBack)
{
loadMyAccount((int) HttpContext.Current.Session["userId"]);
}
}
}
That will prevent your Page_Load from overwriting the user's input.
I have an asp.net webforms c# application that has a FileUpload control inside the InsertItemTemplate of a FormView. When inserting the new record the correct path + filename is saved to the appropriate field in the database, but the file isn't saved to the Data folder. Here is the code behind:
protected void fv_ven_doc_det_DataBound(object sender, EventArgs e)
{
if (fv_ven_doc_det.CurrentMode == FormViewMode.Insert)
{
//Set the fk
TextBox venIdFkTxt = (TextBox)fv_ven_doc_det.FindControl("venIdFkTextBox");
if (venIdFkTxt != null)
{
venIdFkTxt.Text = hdn_ven_id.Value;
}
//Get the upload date - current date and time
hdn_doc_upload_dt_txt.Value = DateTime.Now.ToString();
string docuplddt = fv_ven_doc_det.FindControl("docUpldDtTextBox").ToString();
docuplddt = hdn_doc_upload_dt_txt.Value;
TextBox docuplddttxt = (TextBox)fv_ven_doc_det.FindControl("docUpldDtTextBox");
if (docuplddttxt != null)
{
docuplddttxt.Text = hdn_doc_upload_dt_txt.Value;
}
//Set the current status
TextBox crntDocStatTxt = (TextBox)fv_ven_doc_det.FindControl("docStatTextBox");
if (crntDocStatTxt != null)
{
crntDocStatTxt.Text = "4";
}
//Set the filename and save the file
int i = 0;
FileUpload fu = (FileUpload)(fv_ven_doc_det.FindControl("fu_doc_upld"));
string filename = fu.FileName;
if (fu.HasFile == true)
{
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))
{
i++;
filename = fu.FileName + " (" + i.ToString() + ")";
}
fu.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);
}
TextBox filenameTxt = (TextBox)fv_ven_doc_det.FindControl("docPathTextBox");
{
filenameTxt.Text = (Server.MapPath("~/Data/") + filename);
}
}
}
Here is the InsertItemTemplate of the FormView:
<InsertItemTemplate>
<asp:TextBox Text='<%# Bind("venIdFk") %>' runat="server" ID="venIdFkTextBox" Visible="false" />
<asp:TextBox Text='<%# Bind("docPath") %>' runat="server" ID="docPathTextBox" Visible="false" />
<asp:TextBox Text='<%# Bind("docStat") %>' runat="server" ID="docStatTextBox" Visible="false" />
<asp:TextBox Text='<%# Bind("docUpldDt") %>' runat="server" ID="docUpldDtTextBox" Visible="false" />
<div class="row">
<div class="form-group col-md-3">
<strong>Title</strong><br />
<asp:TextBox Text='<%# Bind("docTitle") %>' runat="server" ID="docTitleTextBox" CssClass="form-control widecontrol" /><br />
</div>
<div class="form-group col-md-3">
<strong>Type</strong><br />
<asp:DropDownList ID="ddlVenDocType" runat="server" DataSourceID="sdc_doc_type" DataTextField="dtype" DataValueField="dtypeId" SelectedValue='<%# Bind("docType") %>' AppendDataBoundItems="true" CssClass="form-control widecontrol"><asp:ListItem Value="">--Please Select--</asp:ListItem></asp:DropDownList><br />
</div>
<div class="form-group col-md-3">
<strong>Organization</strong><br />
<asp:DropDownList ID="ddlVenDocOrg" runat="server" DataSourceID="sdc_orgs" DataTextField="org" DataValueField="orgId" SelectedValue='<%# Bind("docOrg") %>' AppendDataBoundItems="true" CssClass="form-control widecontrol"><asp:ListItem Value="">--Please Select--</asp:ListItem></asp:DropDownList><br />
</div>
<div class="form-group col-md-3">
<strong>Department</strong><br />
<asp:DropDownList ID="ddlVenDocDept" runat="server" DataSourceID="sdc_depts" DataTextField="dept" DataValueField="deptId" SelectedValue='<%# Bind("docDept") %>' AppendDataBoundItems="true" CssClass="form-control widecontrol"><asp:ListItem Value="">--Please Select--</asp:ListItem></asp:DropDownList><br />
</div>
</div>
<div class="row">
<div class="form-group col-md-3">
<strong>Prior Contract Code</strong><br />
<asp:TextBox Text='<%# Bind("PriorContCd") %>' runat="server" ID="PriorContCdTextBox" CssClass="form-control widecontrol" /><br />
</div>
<div class="form-group col-md-3">
<strong>Legal / Compliance Contract ID</strong><br />
<asp:TextBox Text='<%# Bind("LegCompContId") %>' runat="server" ID="LegCompContIdTextBox" CssClass="form-control widecontrol" /><br />
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<strong>Description</strong><br />
<asp:TextBox Text='<%# Bind("docDesc") %>' runat="server" ID="docDescTextBox" CssClass="form-control widecontrol" Rows="5" TextMode="MultiLine" /><br />
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<asp:FileUpload ID="fu_doc_upld" runat="server" />
<asp:RequiredFieldValidator ID="rfv_fu_doc_upld" runat="server" ErrorMessage="A file must be chosen to upload." ControlToValidate="fu_doc_upld" ForeColor="#ff0000" Font-Bold="true">*</asp:RequiredFieldValidator>
</div>
</div>
<asp:LinkButton runat="server" Text="Insert" CommandName="Insert" ID="InsertButton" CausesValidation="True" CssClass="cmdlinkpdg" /> <asp:LinkButton runat="server" Text="Cancel" CommandName="Cancel" ID="InsertCancelButton" CausesValidation="False" CssClass="cmdlinkpdg" />
</InsertItemTemplate>
I'm not getting any errors, it just doesn't save the file.
OK, it helps to stop and think about what actually needs to happen. I moved the filename / path and upload to OnItemInserting and it all works now.
I'm kind of baffled. Can someone help me point out why my validation summary is not showing the custom validators? When I step through the code in the custom validators the args.IsValid is set to false.
<asp:ValidationSummary ID="ValidationSummary1" runat="server" CssClass="alert alert-danger" DisplayMode="List" ShowSummary="true" ValidationGroup="ValidateUser" />
<fieldset class="form-horizontal">
<legend><asp:Literal runat="server" ID="litFirstName" /> <asp:Literal runat="server" ID="litLastName" /><asp:Literal runat="server" id="litLockedBadge" /></legend> <div class="control-group">
<label class="control-label" for="inputEmail">
<asp:CustomValidator ID="cvEmailAddress" runat="server" ValidationGroup="ValidateUser" Text="*" CssClass="required" ControlToValidate="txtEmailAddress" Display="Dynamic" OnServerValidate="cvValidateEmail" />
<asp:RequiredFieldValidator runat="server" CssClass="required" Display="Dynamic" ControlToValidate="txtEmailAddress" Text="*" ErrorMessage="Email Address Required" ValidationGroup="ValidateUser" /> Email Address</label>
<div class="controls">
<asp:Textbox Text="test" runat="server" id="txtEmailAddress" ClientIDMode="Static" CssClass="span3" />
</div>
</div>
<div class="control-group input-append">
<label class="control-label" for="txtUserName"><asp:CustomValidator runat="server" ID="cvUserName" Text="*" CssClass="required" Display="Dynamic" OnServerValidate="cvValidateUserName" ValidationGroup="ValidateUser" /><asp:RequiredFieldValidator runat="server" Display="Dynamic" CssClass="required" ControlToValidate="txtUserName" Text="*" ErrorMessage="Username Required" ValidationGroup="ValidateUser" /> Username</label>
<div class="controls">
<asp:Textbox Text="test" runat="server" id="txtUserName" ClientIDMode="Static" CssClass="span3" />
<asp:LinkButton data-attr="email" ID="lnkEmailUsername" runat="server" CssClass="btn" OnClick="btn_ClickEmailUsername" ClientIDMode="Static"><i class="icon-envelope"></i></asp:LinkButton>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail"></label>
<div class="controls">
<div class="btn-group">
<asp:Button runat="server" ID="btnUnlockAccount" CssClass="btn" Text="Unlock Account" />
<asp:Button runat="server" ID="btnResetPassword" CssClass="btn" Text="Reset Password" />
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail"></label>
<div class="controls">
<asp:Button runat="server" ID="btnSubmit" CssClass="btn btn-primary" Text="Update User Account" OnClick="btn_UpdateUserAccount" ValidationGroup="ValidateUser" />
</div>
</div>
</fieldset>
Here is the code behind
//Validate the Username
protected void cvValidateUserName(object source, ServerValidateEventArgs args)
{
string userName = txtUserName.Text;
cvUserName.ErrorMessage = "";
args.IsValid = true;
if (userName.Contains(" "))
{
cvUserName.ErrorMessage = "Username cannot contain spaces. ";
cvUserName.IsValid = false;
}
if (userName.Length > 100 || userName.Length < 8)
{
cvUserName.ErrorMessage += "Username must be between 8 and 100 characters. ";
cvUserName.IsValid = false;
return;
}
}
//Validate Email Address
protected void cvValidateEmail(object source, ServerValidateEventArgs args)
{
var emailAddress = txtEmailAddress.Text;
try
{
new MailAddress(emailAddress);
}
catch (Exception)
{
args.IsValid = false;
return;
}
}
In order for the Validator's error message to display in the ValidationSummary, you need to set the Validators Display="none". I also set Text="".
I'm trying to user recaptcha control in my application. For some reason it's all the time valid. no matter what values I put in recaptcha field it's all the time valid. Any idea what I'm missing?
here is my code
<%# Control Language="C#" CodeBehind="RegisterControl.ascx.cs" AutoEventWireup="true"
Inherits="UserControls.RegisterControl" %>
<%# Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>
<asp:Panel ID="PlReg" runat="server" DefaultButton="CreateUserButton">
<div class="Reg_Wrapper">
<span class="failureNotification">
<asp:Literal ID="ErrorMessage" runat="server"></asp:Literal>
</span>
<div class="Clear">
</div>
<div class="Reg_ControlName">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label></div>
<div class="Reg_Control">
<asp:TextBox ID="TxtUserName" runat="server" CssClass="textEntry"></asp:TextBox>
<asp:RequiredFieldValidator Display="Dynamic" ID="UserNameRequired" runat="server"
ControlToValidate="TxtUserName" CssClass="failureNotification" ErrorMessage="User Name is required."
ToolTip="User Name is required." ValidationGroup="RegisterUserValidationGroup"><img src="/Images/required.png" alt="Required" /></asp:RequiredFieldValidator>
</div>
<div class="Clear">
</div>
<div class="Reg_ControlName">
<asp:Label ID="EmailLabel" runat="server" AssociatedControlID="Email">E-mail:</asp:Label></div>
<div class="Reg_Control">
<asp:TextBox ID="TxtEmail" runat="server" CssClass="textEntry"></asp:TextBox>
<asp:RequiredFieldValidator Display="Dynamic" ID="EmailRequired" runat="server" ControlToValidate="TxtEmail"
CssClass="failureNotification" ErrorMessage="E-mail is required." ToolTip="E-mail is required."
ValidationGroup="RegisterUserValidationGroup"><img src="/Images/required.png" alt="Required" /></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RevEmail" ControlToValidate="TxtEmail" runat="server"
ErrorMessage="*" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*">
<img src="/Images/required.png" alt="Required" />
</asp:RegularExpressionValidator>
</div>
<div class="Clear">
</div>
<div class="Reg_ControlName">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label></div>
<div class="Reg_Control">
<asp:TextBox ID="TxtPassword" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator Display="Dynamic" ID="PasswordRequired" runat="server"
ControlToValidate="TxtPassword" CssClass="failureNotification" ErrorMessage="Password is required."
ToolTip="Password is required." ValidationGroup="RegisterUserValidationGroup"><img src="/Images/required.png" alt="Required" /></asp:RequiredFieldValidator>
</div>
<div class="Clear">
</div>
<div class="Reg_ControlName">
<asp:Label ID="ConfirmPasswordLabel" runat="server" AssociatedControlID="ConfirmPassword">Conf. Password:</asp:Label></div>
<div class="Reg_Control">
<asp:TextBox ID="TxtConfirmPassword" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="TxtConfirmPassword" CssClass="failureNotification"
Display="Dynamic" ErrorMessage="Confirm Password is required." ID="ConfirmPasswordRequired"
runat="server" ToolTip="Confirm Password is required." ValidationGroup="RegisterUserValidationGroup"><img src="/Images/required.png" alt="Required" /></asp:RequiredFieldValidator>
<asp:CompareValidator ID="PasswordCompare" runat="server" ControlToCompare="TxtPassword"
ControlToValidate="TxtConfirmPassword" CssClass="failureNotification" Display="Dynamic"
ErrorMessage="The Password and Confirmation Password must match." ValidationGroup="RegisterUserValidationGroup"><img src="/Images/required.png" alt="Required" /></asp:CompareValidator>
</div>
<div class="Clear">
</div>
<div class="Reg_ControlName">
</div>
<div class="Reg_Control">
<recaptcha:RecaptchaControl ID="recaptcha" runat="server" PublicKey="my public key"
PrivateKey="my private key" Theme="white" />
</div>
<div class="Clear">
</div>
<div class="Reg_ControlName">
</div>
<div class="Reg_Control">
<asp:Button ID="CreateUserButton" role="button" runat="server" CommandName="MoveNext"
Text="Create User" ValidationGroup="RegisterUserValidationGroup" CssClass="Reg_Button"
OnClick="CreateUserButton_Click" /></div>
<div class="Clear">
</div>
</div>
</asp:Panel>
serverside
protected void CreateUserButton_Click(object sender, EventArgs e)
{
if(Page.IsValid)
{
ErrorMessage.Text = "page is valid";
}
else
{
ErrorMessage.Text = "page is not valid";
}
}
Here's one that works for me. Be sure to insert correct keys on server:
<recaptcha:RecaptchaControl ID="recaptcha" Theme="clean" runat="server"
PublicKey="hiddenxxx" TabIndex="7" ToolTip="Accessible CAPTCHA"
privateKey="hiddenxxx" />
<asp:Label CssClass="captchaLabel" ID="lblResult" runat="server" />
As you can see, I usually keep the CAPTCHA error message separate from the other messages.
Code-behind:
if(Page.IsValid)
{
...
}
else
{
lblResult.Text = "Incorrect!";
lblResult.ForeColor = System.Drawing.Color.Red;
}
i dont think check captcha validation out on page load there should be submit button that you have and you check it out in click event of the button, this is how i use. i think you should check links blove...
http://code.google.com/intl/tr-TR/apis/recaptcha/docs/aspnet.html
http://www.codeproject.com/KB/custom-controls/CaptchaControl.aspx