如何禁用asp.net中必填字段的验证?

时间:2017-03-11 23:24:53

标签: jquery asp.net validation

我有一个表单字段,用于注册新用户。这一切都需要验证。此外,在这个网页中,我有后退按钮。但是,当我按下后退按钮时,验证已完成,并且不允许表单重定向到另一个页面。如何防止后退按钮验证?我可以看到,当表单中缺少字段时,甚至没有触发回发?

这是aspx文件 -

<%@ Page Title="" Language="C#" MasterPageFile="~/DefaultLayout.Master" AutoEventWireup="true" CodeBehind="CreateAccount.aspx.cs" Inherits="SchoolMgmtSystem.Admin.SaveAdminInfo" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="container-fluid">

        <div class="jumbotron" id="divCreateAccount" runat="server" style="display:block">
            <h1>Create Account</h1>
        </div>

        <div class="jumbotron" id="divUpdateAccount" runat="server" style="display:none">
            <h1> Update Account </h1>
        </div>

        <div class="form-group" id="DivRoleUpdate" runat="server" style="display:block">
            <asp:Label ID="LabelRole" runat="server" Text="Role:" CssClass="col-sm-2"></asp:Label>
            <asp:DropDownList ID="DropDownListRoles" runat="server" OnSelectedIndexChanged="DropDownListRoles_SelectedIndexChanged" AutoPostBack="True">
                <asp:ListItem Value="1">Admin</asp:ListItem>
                <asp:ListItem Value="2">Faculty</asp:ListItem>
                <asp:ListItem Value="3">Student</asp:ListItem>
                <asp:ListItem Value="4">Parents</asp:ListItem>
            </asp:DropDownList>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorRoles" runat="server" ErrorMessage="Please select Role ID" ControlToValidate="DropDownListRoles"></asp:RequiredFieldValidator>

        </div>

        <div class="form-group">
            <asp:Label ID="LabelFName" runat="server" Text="First Name:" CssClass="col-sm-2"></asp:Label>
            <asp:TextBox ID="TextBoxFName" runat="server" CssClass="col-sm-3" placeholder="Enter your First Name" AutoPostBack="True"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorFname" runat="server" ErrorMessage="Missing First Name" ControlToValidate="TextBoxFName" ForeColor="#FF3300"></asp:RequiredFieldValidator>
        </div>

        <div class="form-group">
            <asp:Label ID="LabelLName" runat="server" Text="Last Name:" CssClass="col-sm-2"></asp:Label>
            <asp:TextBox ID="TextBoxLName" runat="server" CssClass="col-sm-3" placeholder="Enter your Last Name"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorLname" runat="server" ErrorMessage="Missing Last Name" ControlToValidate="TextBoxLName" ForeColor="#FF3300"></asp:RequiredFieldValidator>

        </div>

        <div class="form-group">
            <asp:Label ID="LabelGender" runat="server" Text="Gender:" CssClass="col-sm-2"></asp:Label>
            <asp:RadioButtonList ID="RadioButtonListGender" runat="server" CssClass="col-sm-3" RepeatDirection="Horizontal">
                <asp:ListItem Value="M">MALE</asp:ListItem>
                <asp:ListItem Value="F">FEMALE</asp:ListItem>
            </asp:RadioButtonList>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorGender" runat="server" ErrorMessage="Select Gender" ControlToValidate="RadioButtonListGender" ForeColor="#FF3300"></asp:RequiredFieldValidator>

        </div>

        <div class="form-group" id="DivFacultyClass" runat="server" style="display:none">
            <asp:Label ID="LabelFacultyClass" runat="server" Text="Class Name:" CssClass="col-sm-2"></asp:Label>
            <asp:CheckBoxList ID="CheckBoxListClasses" runat="server" RepeatDirection="Horizontal" CellPadding="4" CellSpacing="4" ValidateRequestMode="Disabled">
                <asp:ListItem Value="1">Class 1 </asp:ListItem>
                <asp:ListItem Value="2">Class 2 </asp:ListItem>
                <asp:ListItem Value="3">Class 3 </asp:ListItem>
                <asp:ListItem Value="4">Class 4 </asp:ListItem>
                <asp:ListItem Value="5">Class 5 </asp:ListItem>
                <asp:ListItem Value="6">Class 6 </asp:ListItem>
            </asp:CheckBoxList>
            <asp:CustomValidator ID="RequiredFieldValidatorFacultyClass" runat="server" ErrorMessage="Add faculty to atleast 1 class"  onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
        </div>

          <div class="form-group" id="DivStudentClass" runat="server" style="display:none">
            <asp:Label ID="LabelStudentClass" runat="server" Text="Class Name:" CssClass="col-sm-2"></asp:Label>
              <asp:DropDownList ID="DropDownListClass" runat="server">
                  <asp:ListItem Value="1">Class 1</asp:ListItem>
                  <asp:ListItem Value="2">Class 2</asp:ListItem>
                  <asp:ListItem Value="3">Class 3</asp:ListItem>
                  <asp:ListItem Value="4">Class 4</asp:ListItem>
                  <asp:ListItem Value="5">Class 5</asp:ListItem>
                  <asp:ListItem Value="6">Class 6</asp:ListItem>
              </asp:DropDownList>
              <asp:RequiredFieldValidator ID="RequiredFieldValidatorStudentClass" runat="server" ErrorMessage="Add Student to a class" ControlToValidate="DropDownListClass"></asp:RequiredFieldValidator>
        </div>

          <div class="form-group" id="DivParentStudentId" runat="server" style="display:none">
            <asp:Label ID="Label1" runat="server" Text="Student ID:" CssClass="col-sm-2"></asp:Label>
              <asp:TextBox ID="TextBoxStudentID" runat="server"></asp:TextBox>
              <asp:RequiredFieldValidator ID="RequiredFieldValidatorStudentID" runat="server" ErrorMessage="Enter Student ID" ControlToValidate="TextBoxStudentID"></asp:RequiredFieldValidator>
        </div>

        <div class="form-group">
            <asp:Label ID="LabelEmailId" runat="server" Text="Email ID:" CssClass="col-sm-2"></asp:Label>
            <asp:TextBox ID="TextBoxEmailId" runat="server" CssClass="col-sm-3" placeholder="Enter your Email-id" TextMode="Email"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail" runat="server" ErrorMessage="Missing Email Id" ControlToValidate="TextBoxEmailId" ForeColor="#FF3300"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="TextBoxEmailId" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
        </div>

        <div class="form-group" id="DivPassword" runat="server" style="display:block">
            <asp:Label ID="LabelPassword" runat="server" Text="Password:" CssClass="col-sm-2"></asp:Label>
            <asp:TextBox ID="TextBoxPassword" runat="server" CssClass="col-sm-3" placeholder="Enter password" TextMode="Password"></asp:TextBox>
             <asp:RequiredFieldValidator ID="RequiredFieldValidatorPassword" runat="server" ErrorMessage="Missing Password" ControlToValidate="TextBoxPassword" ForeColor="#FF3300"></asp:RequiredFieldValidator>
            <ajaxToolkit:PasswordStrength ID="PasswordStrength1"  runat="server" ViewStateMode="Inherit" MinimumLowerCaseCharacters="1" MinimumUpperCaseCharacters="1" MinimumNumericCharacters="4" MinimumSymbolCharacters="1" PreferredPasswordLength="6" TargetControlID="TextBoxPassword" />
            <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

        </div>

        <div class="form-group" id="DivConfirmPassword" runat="server" style="display:block">
            <asp:Label ID="LabelConfirmPassword" runat="server" Text="Confirm Password:" CssClass="col-sm-2"></asp:Label>
            <asp:TextBox ID="TextBoxConfirmPassword" runat="server" CssClass="col-sm-3" placeholder="Confirm password" TextMode="Password"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorConfirmPassword" runat="server" ErrorMessage="Missing Confirm Password" ControlToValidate="TextBoxConfirmPassword" ForeColor="#FF3300"></asp:RequiredFieldValidator>
            <asp:CompareValidator ID="CompareValidatorPassword" runat="server" ErrorMessage="Confirm Password doesn't match" ControlToCompare="TextBoxPassword" ControlToValidate="TextBoxConfirmPassword"></asp:CompareValidator>
        </div>

        <div class="form-group">
            <asp:Label ID="LabelMobileNumber" runat="server" Text="Mobile Number:" CssClass="col-sm-2"></asp:Label>
            <asp:TextBox ID="TextBoxMobileNumber" runat="server" CssClass="col-sm-3" placeholder="Enter Mobile Number" TextMode="Phone"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorMobileNumber" runat="server" ErrorMessage="Missing Mobile Number" ControlToValidate="TextBoxMobileNumber" ForeColor="#FF3300"></asp:RequiredFieldValidator>
           <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Invalid Mobile Number" ForeColor="Red" ControlToValidate="TextBoxMobileNumber" ValidationExpression="^[0-9]{12}$"></asp:RegularExpressionValidator>
        </div>

        <div class="form-group">
            <asp:Label ID="LabelAddress" runat="server" Text="Address:" CssClass="col-sm-2"></asp:Label>
            <asp:TextBox ID="TextBoxAddress" runat="server" CssClass="col-sm-3" placeholder="Enter Address" AutoCompleteType="None" TextMode="MultiLine"></asp:TextBox>
             <asp:RequiredFieldValidator ID="RequiredFieldValidatorAddress" runat="server" ErrorMessage="Missing Address" ControlToValidate="TextBoxAddress" ForeColor="#FF3300"></asp:RequiredFieldValidator>
        </div>

        <div class="form-group" id ="DivSignUpBtn" runat="server" style="display:block">
            <asp:Button ID="ButtonSignUpAdmin" runat="server" Text="Sign Up" CssClass="btn-primary center-block" OnClick="ButtonSignUpAdmin_Click" />
        </div>
        <div class="form-group" id ="DivUpdateBtn" runat="server" style="display:block">
            <asp:Button ID="ButtonUpdate" runat="server" Text="Update" CssClass="btn-primary center-block" OnClick="ButtonUpdate_Click" />
        </div>

        <div class="form-group" id ="Div1" runat="server" style="display:block">
            <asp:Button ID="ButtonBack" runat="server" Text="Back" CssClass="btn-primary center-block" OnClick="ButtonBack_Click" />
        </div>


    </div>
</asp:Content>

这是我的代码文件 -

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common;
using BAL;

namespace SchoolMgmtSystem.Admin
{
    public partial class SaveAdminInfo : System.Web.UI.Page
    {

       static String GetRoleIdFromRoleName(String Rolename)
        {
           switch(Rolename)
            {
                case "Admin":
                     return "1";

                case "Faculty":
                    return "2";

                case "Student":
                    return "3";

                case "Parent":
                    return "4";

                default:
                    return "0";

            }

        }

        static String GetClassIdFromClasName(String ClassName)
        {
            switch (ClassName)
            {
                case "Class 1":
                    return "1";

                case "Class 2":
                    return "2";

                case "Class 3":
                    return "3";

                case "Class 4":
                    return "4";

                case "Class 5":
                    return "5";
                case "Class 6":
                    return "6";
                default:
                        return "0";

            }

        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {

                DivUpdateBtn.Style.Add("display", "none");
                String RoleId;

                if (Request.QueryString["RoleName"] != null)
                {
                    DivPassword.Style.Add("display", "none");
                    DivConfirmPassword.Style.Add("display", "none");
                    DivSignUpBtn.Style.Add("display", "none");
                    RequiredFieldValidatorPassword.Enabled = false;
                    RequiredFieldValidatorConfirmPassword.Enabled = false;
                    String AdminId = Request.QueryString["Id"];
                    RoleId = GetRoleIdFromRoleName(Request.QueryString["RoleName"].ToString());

                    Common.AdminData AdminData = BAL.AdminBizz.GetFormData(AdminId, RoleId);
                    AdminData.AdminID = AdminId;
                    /** File the update Data **/
                    DropDownListRoles.SelectedValue = AdminData.RoleId.ToString();
                    TextBoxFName.Text = AdminData.Fname;
                    TextBoxLName.Text = AdminData.Lname;
                    TextBoxEmailId.Text = AdminData.EmailId;
                    TextBoxMobileNumber.Text = AdminData.MobileNumber;
                    TextBoxAddress.Text = AdminData.Address;
                    RadioButtonListGender.SelectedValue = AdminData.Gender.ToString();
                    if(RoleId == "2" && AdminData.ClassValue != "")
                    {
                        DivFacultyClass.Style.Add("display", "block");
                        byte classval = Convert.ToByte(AdminData.ClassValue);
                        for (int i = 0; i < 6; i++)
                        {
                            int x = Convert.ToInt32(classval);
                            int statbit = (x >> i) & 1;
                            if (statbit == 1)
                            {
                                ListItem item = CheckBoxListClasses.Items.FindByValue((i + 1).ToString());
                                item.Selected = true;
                            }
                        }

                    }
                    DivSignUpBtn.Style.Add("display", "none");
                    DivUpdateBtn.Style.Add("display", "block");
                    DivRoleUpdate.Style.Add("display", "none");
                    divCreateAccount.Style.Add("display", "none");
                    divUpdateAccount.Style.Add("display", "block");

                    if (RoleId == "1")
                    {
                        RequiredFieldValidatorFacultyClass.Enabled = false;
                        RequiredFieldValidatorStudentClass.Enabled = false;
                        RequiredFieldValidatorStudentID.Enabled = false;
                    }

                    else if (RoleId == "2")
                    {
                        RequiredFieldValidatorStudentClass.Enabled = false;
                        RequiredFieldValidatorStudentID.Enabled = false;

                    }

                    else if (RoleId == "3" && AdminData.ClassID!=null)
                    {
                        RequiredFieldValidatorFacultyClass.Enabled = false;
                        RequiredFieldValidatorStudentID.Enabled = false;
                        DivStudentClass.Style.Add("display", "block");
                        ListItem item = DropDownListClass.Items.FindByValue(GetClassIdFromClasName(AdminData.ClassID.Trim()));
                        item.Selected = true;

                    }

                    else if(RoleId == "4")
                    {
                        RequiredFieldValidatorFacultyClass.Enabled = false;
                        RequiredFieldValidatorStudentClass.Enabled = false;
                        DivParentStudentId.Style.Add("display", "block");

                    }
                }

                // by default Admin ID is selected
                else
                {

                    RequiredFieldValidatorFacultyClass.Enabled = false;
                    RequiredFieldValidatorStudentClass.Enabled = false;
                    RequiredFieldValidatorStudentID.Enabled = false;
                }

            }

        }

        private void ResetControls(Control parent)
        {
            foreach (Control val in parent.Controls)
            {
                if (val.GetType() == typeof(TextBox))
                {
                    ((TextBox)(val)).Text = "";
                }
                if(val.HasControls())
                {
                    ResetControls(val);
                }
            }
        }

        protected void ButtonSignUpAdmin_Click(object sender, EventArgs e)
        {
            Common.AdminData newAdmin = new AdminData();
            /** prepare the data from the Admin Sign-Up form **/
            newAdmin.Fname = TextBoxFName.Text.Trim();
            newAdmin.Lname = TextBoxLName.Text.Trim();
            newAdmin.PasswordHash = Common.Encryption.Encrypt(TextBoxPassword.Text.Trim());
            newAdmin.RoleId = Int32.Parse(DropDownListRoles.SelectedValue);
            newAdmin.Gender = Convert.ToChar(RadioButtonListGender.SelectedValue);
            newAdmin.EmailId = TextBoxEmailId.Text.Trim();
            newAdmin.MobileNumber = TextBoxMobileNumber.Text.Trim();
            newAdmin.Address = TextBoxAddress.Text.Trim();

            // for Faculty
            if(newAdmin.RoleId == 2 )
            {
                byte classVal = 0;
                int index = 0;
                foreach(ListItem item in CheckBoxListClasses.Items)
                {

                    if(item.Selected)
                    {
                        int x = Convert.ToInt32(classVal);
                        int val = x | (1 << index);
                        classVal = Convert.ToByte(val);
                    }
                    index++;
                }
                newAdmin.ClassValue = Convert.ToByte(classVal).ToString();
            }           

            // for student
            if(newAdmin.RoleId == 3)
            {
                newAdmin.ClassID = DropDownListClass.SelectedValue;
            }

            // for parent 
            if( newAdmin.RoleId == 4)
            {
                newAdmin.StudentID = TextBoxStudentID.Text.Trim();
            }

            /*** Save the data to Admin Table **/
            if(BAL.AdminBizz.SaveAdminData(newAdmin) == 0)
            {
                Response.Write("Failed to Add new Admin");
            }
            //else
            //{
            //    ResetControls(this);
            //}

            else
            {
                TextBoxFName.Text = "";
                TextBoxLName.Text = "";
                RadioButtonListGender.ClearSelection();
                TextBoxEmailId.Text = "";
                TextBoxMobileNumber.Text = "";
                TextBoxAddress.Text = "";

            }

        }

        protected void ButtonUpdate_Click(object sender, EventArgs e)
        {

            Common.AdminData newAdmin = new AdminData();
            /** prepare the data from the Admin Sign-Up form **/
            newAdmin.Fname = TextBoxFName.Text.Trim();
            newAdmin.Lname = TextBoxLName.Text.Trim();
            newAdmin.RoleId = Int32.Parse(GetRoleIdFromRoleName(Request.QueryString["RoleName"]));
            newAdmin.Gender = Convert.ToChar(RadioButtonListGender.SelectedValue);
            newAdmin.EmailId = TextBoxEmailId.Text.Trim();
            newAdmin.MobileNumber = TextBoxMobileNumber.Text.Trim();
            newAdmin.Address = TextBoxAddress.Text.Trim();
            newAdmin.AdminID = Request.QueryString["Id"].Trim();
            newAdmin.ClassID = DropDownListClass.SelectedValue.Trim();
            newAdmin.StudentID = TextBoxStudentID.Text.Trim();

            if (newAdmin.RoleId == 2)
            {
                byte classVal = 0;
                int index = 0;
                foreach (ListItem item in CheckBoxListClasses.Items)
                {

                    if (item.Selected)
                    {
                        int x = Convert.ToInt32(classVal);
                        int val = x | (1 << index);
                        classVal = Convert.ToByte(val);
                    }
                    index++;
                }
                newAdmin.ClassValue = Convert.ToByte(classVal).ToString();
            }

            /*** Save the data to Admin Table **/
            if (BAL.AdminBizz.UpdateAdminData(newAdmin) != 0)
            {
                Response.Write("Failed to Add new Admin");
            }
            else
            {
                Response.Redirect("ShowAdminData.aspx");
            }
        }

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = CheckBoxListClasses.SelectedIndex == -1 || DropDownListRoles.SelectedValue != "2"? false : true;
        }

        protected void DropDownListRoles_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Admin selected
            if(DropDownListRoles.SelectedValue == "1")
            {
                DivStudentClass.Style.Add("display", "none");
                DivFacultyClass.Style.Add("display", "none");
                DivParentStudentId.Style.Add("display", "none");
                RequiredFieldValidatorFacultyClass.Enabled = false;
                RequiredFieldValidatorStudentClass.Enabled = false;
                RequiredFieldValidatorStudentID.Enabled = false;


            }
            //Faculty selected
            else if(DropDownListRoles.SelectedValue == "2")
            {
                DivStudentClass.Style.Add("display", "none");
                DivFacultyClass.Style.Add("display", "block");
                DivParentStudentId.Style.Add("display", "none");
                DivFacultyClass.Style.Add("display", "block");
            }
            //Student selected
            else if (DropDownListRoles.SelectedValue == "3")
            {
                DivStudentClass.Style.Add("display", "block");
                DivFacultyClass.Style.Add("display", "none");
                DivParentStudentId.Style.Add("display", "none");

            }
            //Parent selected
            else
            {
                DivStudentClass.Style.Add("display", "none");
                DivFacultyClass.Style.Add("display", "none");
                DivParentStudentId.Style.Add("display", "block");
            }

        }

        protected void ButtonBack_Click(object sender, EventArgs e)
        {

            RequiredFieldValidatorFname.Enabled = false;
            RequiredFieldValidatorLname.Enabled = false;
            RequiredFieldValidatorGender.Enabled = false;
            RequiredFieldValidatorMobileNumber.Enabled = false;
            RequiredFieldValidatorPassword.Enabled = false;
            RequiredFieldValidatorStudentClass.Enabled = false;
            RequiredFieldValidatorStudentID.Enabled = false;
            RequiredFieldValidatorRoles.Enabled = false;
            RequiredFieldValidatorEmail.Enabled = false;
            RequiredFieldValidatorConfirmPassword.Enabled = false;
            RequiredFieldValidatorAddress.Enabled = false;
            String roleId = Request.QueryString["RoleId"];
            String userId = Request.QueryString["UserId"];
            Response.Redirect("MessageSend.aspx?UserId=" + userId + "&RoleId=" + roleId);
        }
    }
}

0 个答案:

没有答案