Can not validate empty input field using c# asp.net - c#

I can not validate for empty input field using c# asp.net. Actually I have two input field. I need to display validation message for blank input field. I have done some coding. When I am clicking on submit button without giving any input, I am getting the error message for first input filed i.e., Name field can not be blank and one red color border on that input field. When I am giving any input to first input field and again clicking on submit button the error message for second input field is coming but problem is border color is showing red in first input field which should not come. I am explaining my code below.
index.aspx:
<div class="widget-title">Doctor Registration <span id="validationMessage" runat="server" ></span></div>
<div class="row doctorlist-form">
<div class="col-md-6 bmargindiv1">
<label for="doctorname" accesskey="N"><span class="required">*</span> Name</label>
<div class="col-md-2 padding-zero">
<asp:DropDownList ID="txtdoctorprefix" name="doctorname" runat="server">
<asp:ListItem Value="Dr." Selected="True" Text="Dr."></asp:ListItem>
<asp:ListItem Value="Mr." Text="Mr."></asp:ListItem>
<asp:ListItem Value="Mrs." Text="Mrs."></asp:ListItem>
</asp:DropDownList>
</div>
<div class="col-md-10 padding-zero"><asp:TextBox ID="txtDoctorName" runat="server" oninput="detectName('dName');" ></asp:TextBox></div>
<div class="clearfix"></div>
</div>
<div class="col-md-6 bmargindiv1">
<label for="gender" accesskey="G"><span class="required">*</span> Gender</label>
<asp:DropDownList ID="txtGender" name="grnder" runat="server" onchange="selectGender('gender');">
<asp:ListItem Text="Select your Gender" Selected="True"></asp:ListItem>
<asp:ListItem Text="Male" Value="male" ></asp:ListItem>
<asp:ListItem Text="Female" Value="female"></asp:ListItem>
</asp:DropDownList>
</div>
<div class="col-md-12 bmargindiv1">
<asp:Button runat="server" Text="Submit" class="button" ID="doctorDetails" OnClick="doctorDetails_Click" />
</div>
</div>
<script type="text/javascript">
function detectName(nameid) {
var type = nameid;
console.log(type);
switch (type) {
case 'dName':
$('#<%=txtDoctorName.ClientID %>').css('border-color', '#e3e3e3');
$('#<%=validationMessage.ClientID %>').empty();
break;
}
}
function selectGender(type) {
var type = type;
switch (type) {
case 'gender':
$('#<%=txtGender.ClientID %>').css('border-color', '#e3e3e3');
$('#<%=validationMessage.ClientID %>').empty();
break;
}
}
</script>
index.aspx.cs:
protected void doctorDetails_Click(object sender, EventArgs e)
{
// Response.Write(txtDoctorName.Text.Trim().Length);
if (txtDoctorName.Text.Trim().Length == 0 )
{
validationMessage.InnerText = "Name field can not be blank.";
validationMessage.Style.Add("color", "red");
txtDoctorName.Focus();
txtDoctorName.BorderColor = System.Drawing.Color.Red;
return;
}
if (txtGender.SelectedIndex==0)
{
validationMessage.InnerText = "Gender field can not be blank.";
validationMessage.Style.Add("color", "red");
txtGender.Focus();
txtGender.BorderColor = System.Drawing.Color.Red;
return;
}
}
My problem is when total field is blank and I am clicking on submit button the error message is coming properly but at the same time when I am giving some input to 1st text field and again clicking on submit button the 1st if statement is also executing along with the second if statement which should not happen. In this case only second if statement should execute. Please help me to resolve this issue.

I strongly recommend using the ASP.NET validation controls. For example:
ASPX Page
<asp:ValidationSummary ID="vs" runat="server" ValidationGroup="Default" />
<asp:TextBox ID="txtDoctorName" runat="server" />
<asp:CustomValidator
ID="cv"
runat="server"
ControlToValidate="txtDoctorName"
ValidateEmptyText="true"
Text="*"
OnServerValidate="ValidateRequired"
ErrorMessage="Please enter a valid Doctor Name."
ValidationGroup="Default" />
Code Behind
protected void SubmitOnClick(object sender, EventArgs e)
{
if (!Page.IsValid) return;
...
}
protected void ValidateRequired(object source, ServerValidateEventArgs args)
{
args.IsValid = !string.IsNullOrEmpty(args.Value.Trim());
}
The ValidationSummary will give you a nice listing of all validation errors, rather than just one at a time.
If you're going to continue with this method, to fix the red border on the first text box not going away, you will need to reset the border color each time the button is clicked:
protected void doctorDetails_Click(object sender, EventArgs e)
{
// Clear all properties each time the button is clicked
validationMessage.InnerText = string.Empty;
txtDoctorName.BorderColor = System.Drawing.Color.Black;
txtGender.BorderColor = System.Drawing.Color.Black;
if (txtDoctorName.Text.Trim().Length == 0 )
{
...
}
You can start your project in Debug mode (F5), place a break point on the doctorDetails_Click method, and step through using F10 to see more details about what's going on.

Since you set the color of the border explicitly on a control that is running at server (runat) - my strong hunch is that the ViewState is preserving these properities.
You can test that behaviour by reversing your code to check on the second input before the first, you may see that red border remains on the second now while (only) the first has failed validation
I agree with #GoatBreeder that you use buitin validation controls,

Related

Why is the textbox in my ASP.NET webform always empty

This is my markup:
<%# Page Title="" Language="C#" MasterPageFile="~/User/Default.Master" AutoEventWireup="true" CodeBehind="Consulation.aspx.cs" Inherits="PetShop.User.Consulation" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script>
window.onload = function () {
var second = 5;
setTimeout(function () {
document.getElementById("<%=lblMsg.ClientID%>").style.display = "none";
}, second * 1000)
}
</script>
<link href="../CSSandJS/StyleCss/consulation.css" rel="stylesheet" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<!-- Slider -->
<section id="Slider">
<div class="aspect-ratio-169">
<img src="../CSSandJS/images/bg_1.jpg" alt="">
<img src="../CSSandJS/images/bg_2.jpg" alt="">
<img src="../CSSandJS/images/bg_3.jpg" alt="">
<img src="../CSSandJS/images/bg_4.jpg" alt="">
</div>
<div class="dot-container">
<div class="dot active"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
</section>
<!-- End Slider -->
<!-- Free Consulation -->
<section class="contact">
<div class="container-contact">
<h1>Đặt lịch hẹn</h1>
<div class="row">
<div class="contact-img">
<img src="../CSSandJS/images/bg_1.jpg" alt="" width="400">
</div>
<div class="input-infor">
<div class="form">
<div class="dbl-field">
<asp:DropDownList ID="ddlCategory" runat="server" CssClass="form-control option field-mail listOp" DataSourceID="SqlDataSource1" DataTextField="TENDV" DataValueField="MADV" AppendDataBoundItems="true">
<asp:ListItem Value="0">Chọn danh mục</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:cs %>" SelectCommand="SELECT [MADV], [TENDV] FROM [DICHVU]"></asp:SqlDataSource>
</div>
<div class="dbl-field">
<div class="field-mail">
<asp:TextBox ID="txtEmail" runat="server" CssClass="form-control input" placeholder="Nhập email" required></asp:TextBox>
<i class="ri-mail-line"></i>
</div>
</div>
<div class="dbl-field">
<div class="field">
<asp:TextBox ID="txtNameAcc" runat="server" CssClass="form-control input" placeholder="Nhập tên"></asp:TextBox>
<i class="ri-user-line"></i>
</div>
<div class="field">
<asp:TextBox ID="txtSDT" runat="server" CssClass="form-control input" placeholder="Nhập số điện thoại" MaxLength="11"></asp:TextBox>
<i class="ri-phone-line"></i>
</div>
</div>
<div class="dbl-field">
<div class="field">
<asp:TextBox ID="txtNgay" runat="server" CssClass="form-control input" TextMode="Date"></asp:TextBox>
<i class="ri-calendar-2-line"></i>
</div>
<div class="field">
<asp:TextBox ID="txtTime" runat="server" CssClass="form-control input" placeholder="Nhập giờ hẹn" MaxLength="5" TextMode="SingleLine"></asp:TextBox>
<i class="ri-time-line"></i>
</div>
</div>
<div class="message">
<asp:TextBox ID="txtDescription" runat="server" CssClass="form-control textarea" placeholder="Tin nhắn" TextMode="MultiLine"></asp:TextBox>
<i class="ri-message-2-line"></i>
</div>
<div class="button-area">
<asp:Button ID="Add" runat="server" Text="Gửi lịch hẹn" class="btn btn-primary button" OnClick="Add_Click"/>
<asp:Label ID="lblMsg" runat="server" Visible="false"></asp:Label>
<%--<asp:linkbutton id="submitcal" runat="server" cssclass="btn btn-primary button" OnClick="Add_Click">gửi lịch hẹn</asp:linkbutton>--%>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- End Free Consulation -->
</asp:Content>
The textbox doesn't get any value when I debug the program.
I have tested the stored procedure in SQL Server and it works fine. But the data returned from the SQL code is empty.
My button submit code:
namespace PetShop.User
{
public partial class Consulation : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
}
private void clear()
{
txtEmail.Text = string.Empty;
txtDescription.Text = string.Empty;
txtNameAcc.Text = string.Empty;
txtSDT.Text = string.Empty;
txtNgay.Text = string.Empty;
txtTime.Text = string.Empty;
ddlCategory.ClearSelection();
}
protected void Add_Click(object sender, EventArgs e)
{
string actionName = string.Empty;
bool isValidToExcute = true;
con = new SqlConnection(Connection.GetConnectionString());
cmd = new SqlCommand("Add_KHaddLH", con);
cmd.Parameters.AddWithValue("#Action", "INSERT4KH");
cmd.Parameters.AddWithValue("#MaDv", ddlCategory.SelectedValue);
cmd.Parameters.AddWithValue("#EMail", txtEmail.Text.Trim());
cmd.Parameters.AddWithValue("#Ten", txtNameAcc.Text.Trim());
cmd.Parameters.AddWithValue("#Sdt", txtSDT.Text.Trim());
cmd.Parameters.AddWithValue("#NgayHen", txtNgay.Text.ToString());
cmd.Parameters.AddWithValue("#GioHen", txtTime.Text.Trim());
cmd.Parameters.AddWithValue("#GhiC", txtDescription.Text.Trim());
if (isValidToExcute)
{
cmd.CommandType = CommandType.StoredProcedure;
try
{
con.Open();
cmd.ExecuteNonQuery();
actionName = "gửi";
lblMsg.Visible = true;
lblMsg.Text = "Lịch hẹn " + actionName + " thành công!";
lblMsg.CssClass = "alert alert-success";
clear();
}
catch (Exception ex)
{
lblMsg.Visible = true;
lblMsg.Text = "Lỗi !!!" + ex.Message;
lblMsg.CssClass = "alert alert-danger";
}
finally
{
con.Close();
}
}
}
}
}
I think the error lies in the page reload, because when submitting it will delete all the data in the textbox and then enter.
I've tried adding some commands to the button but still can't handle that it keeps losing textbox data.
I update code behind and markup.
Support me,
Thank.
Ok, so that helps a boatload.
if we have this code:
protected void Add_Click(object sender, EventArgs e)
{
string actionName = string.Empty;
bool isValidToExcute = true;
Debug.Print(txtEmail.Text);
output:
So, you might want to put a break point in, or simple add some debug.prints, and see which text box controls are "empty". But, just looking at what you have, those text boxes should be ok.
And including page-load, shows that you not say running the "clear" routine you have. (so, having included the page load event eliminates about 100 possible issues here. This is VERY much why posting some of your code allows the public here to eliminate a 100 "back and forth" suggestions.) So, for example, had you included "clear" routine in page load, then of course page load fires each and every time BEFORE a button click event, so code in page load is VERY OFTEN suspect here. But, since you don't have code in page load event, we scratch that off the table.
So, far, the controls look to have values, but I suggest you add a break point, or some debug.prints as per above to be 100% sure that the controls in fact do not have values.
Also, just pasting in some of the markup, we see things like this:
So, you do have stray "garbage" in a number of places. (not good).
As it stands, with the posted markup, I MOST certainly do get/see/have/enjoy/observe that the text boxes are intact, do have values.
Given we can't re-produce your issue?
I suggest creating a blank new page, drop in some of those controls, and try a test button - (don't even bother with the database save code - we NOT gone that far down the debugging road just yet).
So, only thing so far?
Are you 100% sure the text boxes don't have values, and you tested this BEFORE any of the database save code runs?
and do remove the stray "required" markup in that txtEmail box, the editor even HONKS OUT AT YOU that the markup is bad as per above screen shot.
In fact, drop in another button on the form, and its only job would be to debug print out the text boxes - does that work?
As it stands now, you don't have a re-producable error, and the community in general here has not, does not see your error, nor are we the viewing public EVEN able to re-produce that these text boxes don't have values.
As a result, there information we don't have to re-produce the error.
I suggest building a page with just the txtEmail that is blank, and a simple button. if that works, then start adding markup from that other page until it stops working, since we here can't re-produce your issue with the provided code and markup you have provided.
And, since you using a master page, then check if page load in master page has any code that runs on page load.

Maintain collapse state on postback ASP.NET

I have two different forms that collapse and show either one or the other and there's a button to control them.
<div>
<button type="button"
data-toggle="collapse"
data-target=".multi-collapse"
aria-expanded="false"
aria-controls="form1 form2"> Change Form
</button>
<div class="collapse multi-collapse show" id="form1">
<asp:DropDownList AutoPostBack="true"
OnSelectedIndexChanged="SetDdl2ValuesBasedOnWhatIsSelectedOnDdl1"
ID="Ddl1"
runat="server">
</asp:DropDownList>
<asp:DropDownList ID="Ddl2"
runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" OnClick="SubmitBtn"
<\div>
<div class="collapse multi-collapse" id="form2">
<asp:DropDownList AutoPostBack="true"
OnSelectedIndexChanged="SetDdl2ValuesBasedOnWhatIsSelectedOnDdl1"
ID="Ddl1"
runat="server">
</asp:DropDownList>
<asp:DropDownList ID="Ddl2"
runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" OnClick="SubmitBtn"
<\div>
</div>
My problem is that whenever theres a post back I lose the collapse state of the forms and it goes back to the form1 showing and form2 hiding.
I want to save the state of the collapsables so they stay the same after a postback and I don't know how to do it.
I have done this through PageRequestManager, of course preserving the state of one or two divs, in your case there are two but if there are more, the solution I give is quite difficult but functional:
ASPX Code:
Add your controls in UpdatePanel
<div>
<button type="button"
data-toggle="collapse"
data-target=".multi-collapse"
aria-expanded="false"
aria-controls="form1 form2"> Change Form
</button>
<asp:UpdatePanel ID="up" runat="server">
<ContentTemplate>
<div class="collapse multi-collapse show" id="form1">
<asp:DropDownList AutoPostBack="true"
OnSelectedIndexChanged="Ddl1_SelectedIndexChanged"
ID="Ddl1"
runat="server">
</asp:DropDownList>
<asp:DropDownList ID="Ddl2"
runat="server">
</asp:DropDownList>
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" Text="btn1" />
</div>
<div class="collapse multi-collapse" id="form2">
<asp:DropDownList AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
ID="DropDownList1"
runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2"
runat="server">
</asp:DropDownList>
<asp:Button runat="server" ID="Button2" OnClick="Button1_Click1" Text="btn2" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
JavaScript Code:
The event add_beginRequest is an event that is fired when a Postback starts and it is possible to save the DOM state, while add_endRequest is the event that is fired when the panel is updated and the Postback ends, this is where the controls are arranged according to the conditions:
<script type="text/javascript">
var statusForm1 = false,
statusForm2 = false;
var prm = Sys.WebForms.PageRequestManager.getInstance();
function EndRequestHandler(sender, args) {
if (statusForm1) {
$('#form1').collapse('show');
}
if (statusForm2) {
$('#form2').collapse('show');
}
}
function BeginRequestHandler(sender, args) {
statusForm1 = $('#form1').is(":visible");
statusForm2 = $('#form2').is(":visible");
}
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
</script>
There is a simple and straight forward way of doing this which is, adding the class show to the div that you want to actually show. So, in order to do it, you must set both the divs to run at server. Here is my proposed idea for this problem:
<div class="collapse multi-collapse show" id="myform1" runat="server">
<!-- because in aspx, there is already a form1 form which is parent of all elements that runs at server -->
<!-- Other elements go here -->
</div>
<div class="collapse multi-collapse" id="myform2" runat="server">
<!-- Other elements go here -->
</div>
And on server events, you need to hide and show the respective divs by adding the classes to them.
protected void SubmitBtn1(object sender, EventArgs e)
{
// DoStuff();
ShowMyForm1();
}
protected void SubmitBtn2(object sender, EventArgs e)
{
// DoStuff();
ShowMyForm2();
}
protected void SetDdl2ValuesBasedOnWhatIsSelectedOnDdl1(object sender, EventArgs e)
{
// DoStuff();
// I assume this dropdown is in second form div.
ShowMyForm2();
}
private void ShowMyForm1()
{
myform1.Attributes["class"] = "collapse multi-collapse show"; // this will show the div
myform2.Attributes["class"] = "collapse multi-collapse"; // this will hide the div.
}
private void ShowMyForm2()
{
myform1.Attributes["class"] = "collapse multi-collapse"; // this will hide the div
myform2.Attributes["class"] = "collapse multi-collapse show"; // this will show the div
}
Notice, I have given two events for your submit button because it was appearing on both the forms and it had the same ID for it, which is not allowed for server controls. An ID must be unique. And your form2 has all the elements duplicated in it from the form1
So, to differentiate between those elements, You will have to give them different IDs.

My panel fails to show if the user clicks a specific drop down list item

I am attempting to get a <div> to appear when a specific ListItem is selected.
In my code behind I have:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (reportedBefore.SelectedItem.Text=="yes")
{
reportedBeforePanel.Visible = true;
}
else
{
reportedBeforePanel.Visible = false;
}
}
I referred to this article here initially, which stated I needed a few things:
You need to Enable the AutoPostBack of the dropdownlist for raising the OnSelectedIndexChanged event on server side.
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged
Admittedly, I did not have an AutoPostBack before. After adding it, I am afraid for some reason the requested div still does not show.
<asp:DropDownList ID="reportedBefore" CssClass="larger-drop-2" AutoPostBack="true" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="Select" Value="Select"></asp:ListItem>
<asp:ListItem Text="No" Value="No"></asp:ListItem>
<asp:ListItem Text="Yes" Value="Yes"></asp:ListItem>
<asp:ListItem Text="Unsure" Value="Unsure"></asp:ListItem>
</asp:DropDownList>
<asp:Panel ID="reportedBeforePanel" runat="server" Visible="false">
<div id="showDiv">
<label for="yesDetails">
Please provide details
</label>
<asp:TextBox ID="yesDetails" CssClass="third-w-form" runat="server"/>
</div>
</asp:Panel>
Would someone be so kind to help me out here?
The problem is in the following if-condition:
reportedBefore.SelectedItem.Text=="yes"
By this, you are doing a case-sensitive string comparison (this is the default in .NET), but the values in your dropdownlist are written in a different way ("Yes" vs. "yes").
In order to fix this, either perform a case-insensitive string comparison
string.Compare(reportedBefore.SelectedItem.Text, "yes", true) == 0
or change the casing in the if-statement.
C# is case sensitive, so it's "Yes" not "yes":
reportedBeforePanel.Visible = reportedBefore.SelectedItem.Text == "Yes";
Alternatievely you can use this:
reportedBeforePanel.Visible = reportedBefore.SelectedItem.Text.Equals("yes", StringComparison.InvariantCultureIgnoreCase);

Page change its theme on redirect. I don't want to change

Kindly Help What should i do. My Theme is changed when page redirects
Here is ASP.NET Code
<form id="form1" runat="server">
<div id="dvLeft"></div>
<div id="dvRight"></div>
<div id="dvMiddle"></div>
<div id="dvBottom">
<asp:DropDownList ID="ddlTheme" runat="server" AutoPostBack="True">
<asp:ListItem >FirstTheme</asp:ListItem>
<asp:ListItem>SecondTheme</asp:ListItem>
<asp:ListItem>ThirdTheme</asp:ListItem>
</asp:DropDownList>
</div>
</form>
And Here is C# Code:
protected override void OnPreInit(EventArgs e)
{
if (Request["ddlTheme"] != null)
{
string theme = Request["ddlTheme"].ToString();
Page.Theme = theme;
}
base.OnPreInit(e);
}
I'd suggest you set selected theme value in the PreRender event handler instead of PreInit because of the way ASPX page life cycle works.
Below is revised version from your original code
<form id="form1" runat="server">
<div id="dvLeft"></div>
<div id="dvRight"></div>
<div id="dvMiddle"></div>
<div id="dvBottom">
<asp:DropDownList ID="ddlTheme" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlTheme_SelectedIndexChanged">
<asp:ListItem Value="FirstTheme">FirstTheme</asp:ListItem>
<asp:ListItem Value="SecondTheme">SecondTheme</asp:ListItem>
<asp:ListItem Value="ThirdTheme">ThirdTheme</asp:ListItem>
</asp:DropDownList>
</div>
</form>
protected void ddlTheme_SelectedIndexChanged(object sender, EventArgs e)
{
// save value into a session variable
Session["SelectedTheme"] = ddlTheme.SelectedValue;
}
protected void PreRender()
{
// works when page reloads
if (Session["SelectedTheme"] != null){
Page.Theme = Session["SelectedTheme"].ToString();
}
// following line works on postback only
//Page.Theme = ddlTheme.SelectedValue;
}
Update
My original suggestion would only work on postback because when the page reloads, a new page life cycle begins and the selected value from the drop down list would be lost.
However, there's a way to persist the change, which is to use session. To do this, you will attach a new event handler OnSelectedIndexChanged where you can save the selected value into a session variable. Then read this value from session after page reloads. See the added code snippet above.

How to redirect to another page after a delay

I have a sign-in box in my webpage which is inside an UpdatePanel
<asp:UpdatePanel runat="server" ClientIDMode="Static" ID="upSign" UpdateMode="Conditional">
<ContentTemplate>
<div class="dvHolder hidOverflow clearfix">
<input id="txtSUser" type="text" name="SUsername" value="" placeholder="Username" runat="server" />
</div>
<div class="dvHolder hidOverflow clearfix">
<input id="txtSPass" type="password" name="SPassword" value="" placeholder="Password" runat="server" />
</div>
<div class="dvHolder hidOverflow clearfix setTextRight">
<asp:Button ID="btnSignIn" ClientIDMode="Static" runat="server" Text="Sign In" OnClick="btnSignIn_Click" />
<asp:Label runat="server" Text="" ID="lblSSuccess" ClientIDMode="Static" CssClass="lblMsgSuccess" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
Once the user is validated successfully, I want to show a message and redirect after a delay (let's say 5 seconds). I have the following code but it is not redirecting:
public void btnSignIn_Click(object sender, EventArgs e)
{
lblSSuccess.Text = "We found you, now redirecting...";
lblSSuccess.ForeColor = ColorTranslator.FromHtml("#037203");
Session["UseIsAuthenticated"] = "true";
Response.AppendHeader("Refresh", "5;url=homepage.aspx");
}
The message is updated but the page is not redirecting for some reason.
Please help me resolve the issue.
You can write a block of Javascript with a delay and redirect to the page with this code
public void btnSignIn_Click(object sender, EventArgs e)
{
lblSSuccess.Text = "We found you, now redirecting...";
lblSSuccess.ForeColor = ColorTranslator.FromHtml("#037203");
Session["UseIsAuthenticated"] = "true";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "redirectJS",
"setTimeout(function() { window.location.replace('homepage.aspx') }, 5000);", true);
}
There are many ways to do this but I love to use this code because it works well when used in many different circumstances. This is with a 5 second delay.
HtmlMeta oScript = new HtmlMeta();
oScript.Attributes.Add("http-equiv", "REFRESH");
oScript.Attributes.Add("content", "5; url='http://www.myurl.com/'");
Page.Header.Controls.Add(oScript);
first create a function that makes the action you need (redirect to page for example)
Second add timer to your markup and set the time interval to 5000 ( 5 sec) and mark the timer as enabled=false so the timer wont start after the page loading
once the user is validated successfully, show the message you want then enable the timer
Response.AppendHeader("Refresh", "2;url=page.aspx");

Categories