Link to home
Start Free TrialLog in
Avatar of Brian
BrianFlag for United States of America

asked on

ASP.NET Validation Issues

Hello Experts,

I have an issue that I just can't seem to figure out. I have an online form that users enter their information. Just about every field has an ASP.NET Required Field Validation assigned to it. So you cannot submit the form unless those fields are filled out, at least I thought so until today when I saw an entry with just First and Last Name and not other data for that user except the unique ID that was generated by the database.

I had head that if you disable JavaScript that sometimes it can still happen, so I did disable JavaScript but it through up errors since ASP.NET Validation uses JavaScript on the client side.

So, I need to know what I need to implement in my code below to prevent entries from getting submitted if by somehow they get around the client side validation that ASP.NET uses.

Please help!!

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class _default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        txtCurrentlyReceiveOtherInfo.Visible = false;
        lblCurrentlyReceiveExplain.Visible = false;

        if (!IsPostBack)
        {
            ddlState.AppendDataBoundItems = true;

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "RetrieveStateData";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            try
            {
                conn.Open();

                ddlState.DataSource = cmd.ExecuteReader();
                ddlState.DataTextField = "state_name";
                ddlState.DataValueField = "state_id";
                ddlState.DataBind();
            }

            catch (Exception ex)
            {
                throw ex;
            }

            finally
            {
                conn.Close();
                conn.Dispose();
            }

            RetrieveSchoolData();
            RetrieveGradeData();
            RetrieveAgeData();
            RetrieveHearAboutUsValues();
            RetrieveFinancialAssistanceData();
            RetrieveCurrentlyReceieveData();
            RetrieveExtenuatingData();
        }
    }
    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlCity.Items.Clear();
        ddlCity.Items.Add(new ListItem("--Select--", ""));
        ddlZipCode.Items.Clear();
        ddlZipCode.Items.Add(new ListItem("--Select--", ""));

        ddlCity.AppendDataBoundItems = true;

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveCityData";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@state_id", ddlState.SelectedItem.Value);

        try
        {
            conn.Open();
            ddlCity.DataSource = cmd.ExecuteReader();
            ddlCity.DataTextField = "city_name";
            ddlCity.DataValueField = "city_id";
            ddlCity.DataBind();

            if (ddlCity.Items.Count > 1)
            {
                ddlCity.Enabled = true;
            }
            else
            {
                ddlCity.Enabled = false;
                ddlZipCode.Enabled = false;
            }
        }

        catch (Exception ex)
        {
            throw ex;
        }

        finally
        {
            conn.Close();
            conn.Dispose();
        }
    }

    protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlZipCode.Items.Clear();
        ddlZipCode.Items.Add(new ListItem("--Select--", ""));
        ddlZipCode.AppendDataBoundItems = true;

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveZipCodeData";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@city_id", ddlCity.SelectedItem.Value);

        try
        {
            conn.Open();

            ddlZipCode.DataSource = cmd.ExecuteReader();
            ddlZipCode.DataTextField = "zip_code";
            ddlZipCode.DataValueField = "zip_id";
            ddlZipCode.DataBind();

            if (ddlZipCode.Items.Count > 1)
            {
                ddlZipCode.Enabled = true;
            }
            else
            {
                ddlZipCode.Enabled = false;
            }
        }

        catch (Exception ex)
        {
            throw ex;
        }

        finally
        {
            conn.Close();
            conn.Dispose();
        }
    }

    protected void ddlZipCode_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void RetrieveSchoolData()
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveSchoolData";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        try
        {
            conn.Open();

            ddlSchool.DataSource = cmd.ExecuteReader();
            ddlSchool.DataTextField = "sch_name";
            ddlSchool.DataValueField = "sch_id";
            ddlSchool.DataBind();
        }

        catch (Exception ex)
        {
            throw ex;
        }

        finally
        {
            conn.Close();
            conn.Dispose();
        }
    }

    protected void RetrieveGradeData()
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveGradeData";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        try
        {
            conn.Open();

            ddlGrade.DataSource = cmd.ExecuteReader();
            ddlGrade.DataTextField = "grade_name";
            ddlGrade.DataValueField = "grade_id";
            ddlGrade.DataBind();
        }

        catch (Exception ex)
        {
            throw ex;
        }

        finally
        {
            conn.Close();
            conn.Dispose();
        }
    }

    protected void RetrieveAgeData()
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveAgeData";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        try
        {
            conn.Open();

            ddlAge.DataSource = cmd.ExecuteReader();
            ddlAge.DataTextField = "age_name";
            ddlAge.DataValueField = "age_id";
            ddlAge.DataBind();
        }

        catch (Exception ex)
        {
            throw ex;
        }

        finally
        {
            conn.Close();
            conn.Dispose();
        }
    }

    protected void RetrieveHearAboutUsValues()
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveHearAboutUsData";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        try
        {
            conn.Open();

            ddlHearAboutUs.DataSource = cmd.ExecuteReader();
            ddlHearAboutUs.DataTextField = "hau_name";
            ddlHearAboutUs.DataValueField = "hau_id";
            ddlHearAboutUs.DataBind();
        }

        catch (Exception ex)
        {
            throw ex;
        }

        finally
        {
            conn.Close();
            conn.Dispose();
        }
    }

    protected void RetrieveFinancialAssistanceData()
    {
        DataTable dtFinancialAssistanceValues = new DataTable();

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveFinancialAssistanceData";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        SqlDataAdapter adp = new SqlDataAdapter();
        adp.SelectCommand = cmd;
        adp.Fill(dtFinancialAssistanceValues);

        try
        {
            conn.Open();

            cblFinancialAssistanceValues.DataSource = dtFinancialAssistanceValues;
            cblFinancialAssistanceValues.DataValueField = "fa_id";
            cblFinancialAssistanceValues.DataTextField = "fa_name";
            cblFinancialAssistanceValues.DataBind();
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }

    protected void RetrieveCurrentlyReceieveData()
    {
        DataTable dtCurrentlyReceiveValues = new DataTable();

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveCurrentlyReceiveData";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        SqlDataAdapter adp = new SqlDataAdapter();
        adp.SelectCommand = cmd;
        adp.Fill(dtCurrentlyReceiveValues);

        try
        {
            conn.Open();

            cblCurrentlyReceiveValues.DataSource = dtCurrentlyReceiveValues;
            cblCurrentlyReceiveValues.DataValueField = "cr_id";
            cblCurrentlyReceiveValues.DataTextField = "cr_name";
            cblCurrentlyReceiveValues.DataBind();
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }

    protected void RetrieveExtenuatingData()
    {
        DataTable dtExtenuating = new DataTable();

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "RetrieveExtenuatingData";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        SqlDataAdapter adp = new SqlDataAdapter();
        adp.SelectCommand = cmd;
        adp.Fill(dtExtenuating);

        try
        {
            conn.Open();

            cblExtenuating.DataSource = dtExtenuating;
            cblExtenuating.DataValueField = "ex_id";
            cblExtenuating.DataTextField = "ex_name";
            cblExtenuating.DataBind();
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }

    protected void SendEmail()
    {
        SmtpClient smtpClient = new SmtpClient();
        MailMessage message = new MailMessage();

        //MailAddress fromAddress = new MailAddress(HttpUtility.HtmlEncode(txtEmail.Text));
        MailAddress fromAddress = new MailAddress("noreply@team.org", "noreply@team.org");
        MailAddress toAddress = new MailAddress("bill@team.org", "bill@team.org");

        message.From = fromAddress;
        message.To.Add(toAddress);

        message.Subject = "Form";
        message.IsBodyHtml = true;
        message.Body = "<html><head><title>" + "</title></head><body>" + "<h3>** Attention Bill **</h3>" + "<p>A possible candidate just submitted the Financial Assistance Evaluation Form.</p>" + "<p><a href='http://cms.test.org'>view candidate's form</a></p>" + "</body></html>";
        //message.Body = "<html><head><title>" + "</title></head><body>" + "<p>" + "<span style=\"font-size: 16px; color: #0091c1; font-family: Arial\">A candidate just filled out the Financial Evaluation Form.<font face='arial' color='#474747'>" + "<br /><br />" + "<span style=\"font-size: 14px; color: #ff6d00; font-family: Arial\"><b>Username:&nbsp;</b><font face='arial' color='#666666'>" + HttpUtility.HtmlEncode(txtFirstName.Text) + "<br />" + "<span style=\"font-size: 14px; color: #ff6d00; font-family: Arial\"><b>Password:&nbsp;</b><font face='arial' color='##ff6d00; '>" + "<span style=\"font-size: 14px; font-style: italic; color: #aa4900; font-family: Arial\">" + "** Passwords are secure. Please make sure that you remember your password or store it in a safe place. **" + "</body></html>";

        //smtpClient.Host = "smtpout.secureserver.net";
        //smtpClient.Credentials = new System.Net.NetworkCredential("test@test.com", "test");
        smtpClient.Send(message);
    }

    protected void btnSubmitApplication_Click(object sender, EventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString))
        {
            SqlCommand cmdCurrentlyReceive = new SqlCommand();
            cmdCurrentlyReceive.CommandText = "InsertCandidateCurrentlyReceive";
            cmdCurrentlyReceive.CommandType = CommandType.StoredProcedure;
            cmdCurrentlyReceive.Connection = conn;

            SqlCommand cmdFinancialAssistance = new SqlCommand();
            cmdFinancialAssistance.CommandText = "InsertFinancialAssistance";
            cmdFinancialAssistance.CommandType = CommandType.StoredProcedure;
            cmdFinancialAssistance.Connection = conn;

            SqlCommand cmdExtenuating = new SqlCommand();
            cmdExtenuating.CommandText = "InsertExtenuating";
            cmdExtenuating.CommandType = CommandType.StoredProcedure;
            cmdExtenuating.Connection = conn;

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "InsertCandidate";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.Add("@state_id", SqlDbType.Int).Value = ddlState.SelectedValue;
            cmd.Parameters.Add("@city_id", SqlDbType.Int).Value = ddlCity.SelectedValue;
            cmd.Parameters.Add("@zip_id", SqlDbType.Int).Value = ddlZipCode.SelectedValue;
            cmd.Parameters.Add("@sch_id", SqlDbType.Int).Value = ddlSchool.SelectedValue;
            cmd.Parameters.Add("@grade_id", SqlDbType.Int).Value = ddlGrade.SelectedValue;
            cmd.Parameters.Add("@age_id", SqlDbType.Int).Value = ddlAge.SelectedValue;
            cmd.Parameters.Add("@hau_id", SqlDbType.Int).Value = ddlHearAboutUs.SelectedValue;

            cmd.Parameters.Add("@c_fname", SqlDbType.VarChar).Value = txtFirstName.Text;
            //cmd.Parameters.Add("@c_fname", SqlDbType.VarBinary).Value = EncryptDecryptUtil.EncryptObject(txtFirstName.Text);

            cmd.Parameters.Add("@c_lname", SqlDbType.VarChar).Value = txtLastName.Text;
            //cmd.Parameters.Add("@c_lname", SqlDbType.VarBinary).Value = EncryptDecryptUtil.EncryptObject(txtLastName.Text);

            cmd.Parameters.Add("@c_address", SqlDbType.VarChar).Value = txtAddress.Text;
            //cmd.Parameters.Add("@c_address", SqlDbType.VarBinary).Value = EncryptDecryptUtil.EncryptObject(txtAddress.Text);

            cmd.Parameters.Add("@c_phone", SqlDbType.VarChar).Value = txtPhone.Text;
            //cmd.Parameters.Add("@c_phone", SqlDbType.VarBinary).Value = EncryptDecryptUtil.EncryptObject(txtPhone.Text);

            cmd.Parameters.Add("@c_email", SqlDbType.VarChar).Value = txtEmail.Text;
            //cmd.Parameters.Add("@c_email", SqlDbType.VarBinary).Value = EncryptDecryptUtil.EncryptObject(txtEmail.Text);

            cmd.Parameters.Add("@c_purpose_desc", SqlDbType.VarChar).Value = txtPurposeApp.Text;
            cmd.Parameters.Add("@c_crname", SqlDbType.VarChar).Value = txtCurrentlyReceiveOtherInfo.Text;
            cmd.Parameters.Add("@c_amount_requested", SqlDbType.VarChar).Value = txtAmountRequested.Text;
            cmd.Parameters.Add("@c_extenuating_desc", SqlDbType.VarChar).Value = txtExtenuatingDesc.Text;
            cmd.Parameters.Add("@c_parentguardian_name", SqlDbType.VarChar).Value = txtParentGuardianFirstLastName.Text;

            try
            {
                conn.Open();

                int c_id = Convert.ToInt32(cmd.ExecuteScalar());

                cmdCurrentlyReceive.Parameters.Add("@c_id", SqlDbType.Int).Value = c_id;
                cmdCurrentlyReceive.Parameters.Add("@cr_id", SqlDbType.Int);

                foreach (ListItem item in cblCurrentlyReceiveValues.Items)
                {
                    if (item.Selected)
                    {
                        cmdCurrentlyReceive.Parameters["@cr_id"].Value = item.Value;
                        cmdCurrentlyReceive.ExecuteNonQuery();
                    }
                }

                cmdFinancialAssistance.Parameters.Add("@c_id", SqlDbType.Int).Value = c_id;
                cmdFinancialAssistance.Parameters.Add("@fa_id", SqlDbType.Int);

                foreach (ListItem item in cblFinancialAssistanceValues.Items)
                {
                    if (item.Selected)
                    {
                        cmdFinancialAssistance.Parameters["@fa_id"].Value = item.Value;
                        cmdFinancialAssistance.ExecuteNonQuery();
                    }
                }

                cmdExtenuating.Parameters.Add("@c_id", SqlDbType.Int).Value = c_id;
                cmdExtenuating.Parameters.Add("@ex_id", SqlDbType.Int);

                foreach (ListItem item in cblExtenuating.Items)
                {
                    if (item.Selected)
                    {
                        cmdExtenuating.Parameters["@ex_id"].Value = item.Value;
                        cmdExtenuating.ExecuteNonQuery();
                    }
                }

                btnSubmitApplication.Enabled = false;

                SendEmail();
                Response.Redirect("success.aspx");
            }

            catch (Exception ex)
            {
                Response.Write(ex);
                btnSubmitApplication.Enabled = true;
            }
        }
    }

    protected void cblCurrentlyReceiveValues_SelectedIndexChanged(object sender, EventArgs e)
    {
        var strtext = cblCurrentlyReceiveValues.SelectedIndex.ToString();

        if (cblCurrentlyReceiveValues.SelectedIndex != -1)
        {
            strtext = cblCurrentlyReceiveValues.SelectedItem.Text;
        }

        if (strtext == "Other Government Assistance")
        {
            if (cblCurrentlyReceiveValues.SelectedItem.Selected)
            {
                txtCurrentlyReceiveOtherInfo.Visible = true;
                lblCurrentlyReceiveExplain.Visible = true;
            }
            else
            {
                txtCurrentlyReceiveOtherInfo.Visible = false;
                lblCurrentlyReceiveExplain.Visible = false;
            }
        }
        else
        {
            txtCurrentlyReceiveOtherInfo.Visible = false;
            lblCurrentlyReceiveExplain.Visible = false;
        }
    }
}

Open in new window

Avatar of Paul Jackson
Paul Jackson
Flag of United Kingdom of Great Britain and Northern Ireland image

You need to use  Page.isValid in btnSubmitApplication_Click to ensure the validators have fired:

//Proceed only if the vaidation is successful
if (!Page.IsValid) { 
    return;
}

//Insert data into SQL
...
...
...

Open in new window


Have a look at this link which explains it in detail:

http://weblogs.asp.net/rajbk/archive/2007/03/15/page-isvalid-and-validate.aspx
Avatar of Brian

ASKER

Hi jacko72,

So do I need to wrap my code into what you provided like the following below?

protected void btnSubmitApplication_Click(object sender, EventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString))
        {
            SqlCommand cmdCurrentlyReceive = new SqlCommand();
            cmdCurrentlyReceive.CommandText = "InsertCandidateCurrentlyReceive";
            cmdCurrentlyReceive.CommandType = CommandType.StoredProcedure;
            cmdCurrentlyReceive.Connection = conn;

            SqlCommand cmdFinancialAssistance = new SqlCommand();
            cmdFinancialAssistance.CommandText = "InsertFinancialAssistance";
            cmdFinancialAssistance.CommandType = CommandType.StoredProcedure;
            cmdFinancialAssistance.Connection = conn;

            SqlCommand cmdExtenuating = new SqlCommand();
            cmdExtenuating.CommandText = "InsertExtenuating";
            cmdExtenuating.CommandType = CommandType.StoredProcedure;
            cmdExtenuating.Connection = conn;

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "InsertCandidate";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.Add("@state_id", SqlDbType.Int).Value = ddlState.SelectedValue;
            cmd.Parameters.Add("@city_id", SqlDbType.Int).Value = ddlCity.SelectedValue;
            cmd.Parameters.Add("@zip_id", SqlDbType.Int).Value = ddlZipCode.SelectedValue;
            cmd.Parameters.Add("@sch_id", SqlDbType.Int).Value = ddlSchool.SelectedValue;
            cmd.Parameters.Add("@grade_id", SqlDbType.Int).Value = ddlGrade.SelectedValue;
            cmd.Parameters.Add("@age_id", SqlDbType.Int).Value = ddlAge.SelectedValue;
            cmd.Parameters.Add("@hau_id", SqlDbType.Int).Value = ddlHearAboutUs.SelectedValue;
            cmd.Parameters.Add("@c_fname", SqlDbType.VarChar).Value = txtFirstName.Text;
            cmd.Parameters.Add("@c_lname", SqlDbType.VarChar).Value = txtLastName.Text;
            cmd.Parameters.Add("@c_address", SqlDbType.VarChar).Value = txtAddress.Text;
            cmd.Parameters.Add("@c_phone", SqlDbType.VarChar).Value = txtPhone.Text;
            cmd.Parameters.Add("@c_email", SqlDbType.VarChar).Value = txtEmail.Text;
            cmd.Parameters.Add("@c_purpose_desc", SqlDbType.VarChar).Value = txtPurposeApp.Text;
            cmd.Parameters.Add("@c_crname", SqlDbType.VarChar).Value = txtCurrentlyReceiveOtherInfo.Text;
            cmd.Parameters.Add("@c_amount_requested", SqlDbType.VarChar).Value = txtAmountRequested.Text;
            cmd.Parameters.Add("@c_extenuating_desc", SqlDbType.VarChar).Value = txtExtenuatingDesc.Text;
            cmd.Parameters.Add("@c_parentguardian_name", SqlDbType.VarChar).Value = txtParentGuardianFirstLastName.Text;

            try
            {
                conn.Open();

                int c_id = Convert.ToInt32(cmd.ExecuteScalar());

                cmdCurrentlyReceive.Parameters.Add("@c_id", SqlDbType.Int).Value = c_id;
                cmdCurrentlyReceive.Parameters.Add("@cr_id", SqlDbType.Int);

                foreach (ListItem item in cblCurrentlyReceiveValues.Items)
                {
                    if (item.Selected)
                    {
                        cmdCurrentlyReceive.Parameters["@cr_id"].Value = item.Value;
                        cmdCurrentlyReceive.ExecuteNonQuery();
                    }
                }

                cmdFinancialAssistance.Parameters.Add("@c_id", SqlDbType.Int).Value = c_id;
                cmdFinancialAssistance.Parameters.Add("@fa_id", SqlDbType.Int);

                foreach (ListItem item in cblFinancialAssistanceValues.Items)
                {
                    if (item.Selected)
                    {
                        cmdFinancialAssistance.Parameters["@fa_id"].Value = item.Value;
                        cmdFinancialAssistance.ExecuteNonQuery();
                    }
                }

                cmdExtenuating.Parameters.Add("@c_id", SqlDbType.Int).Value = c_id;
                cmdExtenuating.Parameters.Add("@ex_id", SqlDbType.Int);

                foreach (ListItem item in cblExtenuating.Items)
                {
                    if (item.Selected)
                    {
                        cmdExtenuating.Parameters["@ex_id"].Value = item.Value;
                        cmdExtenuating.ExecuteNonQuery();
                    }
                }

                btnSubmitApplication.Enabled = false;

                SendEmail();
                Response.Redirect("success.aspx");
            }

            catch (Exception ex)
            {
                Response.Write(ex);
                btnSubmitApplication.Enabled = true;
            }
        }
    }

Open in new window

No need to wrap just put it before your code if the Page is not valid control will return back to the page without any update occurring.

protected void btnSubmitApplication_Click(object sender, EventArgs e)
{

    //Proceed only if the vaidation is successful
    if (!Page.IsValid) { 
         return;
    }

    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString))
        {
            SqlCommand cmdCurrentlyReceive = new SqlCommand();
            cmdCurrentlyReceive.CommandText = "InsertCandidateCurrentlyReceive";
            cmdCurrentlyReceive.CommandType = CommandType.StoredProcedure;
            cmdCurrentlyReceive.Connection = conn;

            SqlCommand cmdFinancialAssistance = new SqlCommand();
            cmdFinancialAssistance.CommandText = "InsertFinancialAssistance";
            cmdFinancialAssistance.CommandType = CommandType.StoredProcedure;
            cmdFinancialAssistance.Connection = conn;

            SqlCommand cmdExtenuating = new SqlCommand();
            cmdExtenuating.CommandText = "InsertExtenuating";
            cmdExtenuating.CommandType = CommandType.StoredProcedure;
            cmdExtenuating.Connection = conn;

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "InsertCandidate";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.Add("@state_id", SqlDbType.Int).Value = ddlState.SelectedValue;
            cmd.Parameters.Add("@city_id", SqlDbType.Int).Value = ddlCity.SelectedValue;
            cmd.Parameters.Add("@zip_id", SqlDbType.Int).Value = ddlZipCode.SelectedValue;
            cmd.Parameters.Add("@sch_id", SqlDbType.Int).Value = ddlSchool.SelectedValue;
            cmd.Parameters.Add("@grade_id", SqlDbType.Int).Value = ddlGrade.SelectedValue;
            cmd.Parameters.Add("@age_id", SqlDbType.Int).Value = ddlAge.SelectedValue;
            cmd.Parameters.Add("@hau_id", SqlDbType.Int).Value = ddlHearAboutUs.SelectedValue;
            cmd.Parameters.Add("@c_fname", SqlDbType.VarChar).Value = txtFirstName.Text;
            cmd.Parameters.Add("@c_lname", SqlDbType.VarChar).Value = txtLastName.Text;
            cmd.Parameters.Add("@c_address", SqlDbType.VarChar).Value = txtAddress.Text;
            cmd.Parameters.Add("@c_phone", SqlDbType.VarChar).Value = txtPhone.Text;
            cmd.Parameters.Add("@c_email", SqlDbType.VarChar).Value = txtEmail.Text;
            cmd.Parameters.Add("@c_purpose_desc", SqlDbType.VarChar).Value = txtPurposeApp.Text;
            cmd.Parameters.Add("@c_crname", SqlDbType.VarChar).Value = txtCurrentlyReceiveOtherInfo.Text;
            cmd.Parameters.Add("@c_amount_requested", SqlDbType.VarChar).Value = txtAmountRequested.Text;
            cmd.Parameters.Add("@c_extenuating_desc", SqlDbType.VarChar).Value = txtExtenuatingDesc.Text;
            cmd.Parameters.Add("@c_parentguardian_name", SqlDbType.VarChar).Value = txtParentGuardianFirstLastName.Text;

            try
            {
                conn.Open();

                int c_id = Convert.ToInt32(cmd.ExecuteScalar());

                cmdCurrentlyReceive.Parameters.Add("@c_id", SqlDbType.Int).Value = c_id;
                cmdCurrentlyReceive.Parameters.Add("@cr_id", SqlDbType.Int);

                foreach (ListItem item in cblCurrentlyReceiveValues.Items)
                {
                    if (item.Selected)
                    {
                        cmdCurrentlyReceive.Parameters["@cr_id"].Value = item.Value;
                        cmdCurrentlyReceive.ExecuteNonQuery();
                    }
                }

                cmdFinancialAssistance.Parameters.Add("@c_id", SqlDbType.Int).Value = c_id;
                cmdFinancialAssistance.Parameters.Add("@fa_id", SqlDbType.Int);

                foreach (ListItem item in cblFinancialAssistanceValues.Items)
                {
                    if (item.Selected)
                    {
                        cmdFinancialAssistance.Parameters["@fa_id"].Value = item.Value;
                        cmdFinancialAssistance.ExecuteNonQuery();
                    }
                }

                cmdExtenuating.Parameters.Add("@c_id", SqlDbType.Int).Value = c_id;
                cmdExtenuating.Parameters.Add("@ex_id", SqlDbType.Int);

                foreach (ListItem item in cblExtenuating.Items)
                {
                    if (item.Selected)
                    {
                        cmdExtenuating.Parameters["@ex_id"].Value = item.Value;
                        cmdExtenuating.ExecuteNonQuery();
                    }
                }

                btnSubmitApplication.Enabled = false;

                SendEmail();
                Response.Redirect("success.aspx");
            }

            catch (Exception ex)
            {
                Response.Write(ex);
                btnSubmitApplication.Enabled = true;
            }
        }
}

Open in new window

Some more info on validation in asp.net from msdn:

http://msdn.microsoft.com/en-us/library/aa479045.aspx
Avatar of Brian

ASKER

Hi Jacko72,

I'm also using the validation summary. Do I need to include the Page.Validate(); before using if (!Page.IsValid)
{
Return
}

Also do I need to include anything else other than just return for !Page.IsValid ?

What exactly does return do within !Page.IsValid ?

Thanks again for your help with this post!!
No you do not need to include Page.Validate as that is done by default when the submit button is clicked assuming that you have the CausesValidation attribute set to True on your submit button which you would have needed to do to make the client-side validation to work as well.
Return just stops processing of the current function (i.e. stops the saving of the data submitted) and page execution will continue and reshow the submitted page with any errors displayed.

What you need to remember is that client-side validation is done in an attempt to stop a wasteful trip to the server with invalid data. Once the data has been validated on the client the data is submitted to the server and all the same validation is done again on the server, the result of which is checked by examining the value of Page.IsValid. If any of the validation fails on the server-side then in the same way as on the client-side validation the validation controls that have failed will be made visible and will populate the validation summary with any error messages.
So you should always check the value of Page.IsValid before processing the data in your server-side event that is handling the submit button click.
Avatar of Brian

ASKER

Hi jacko72,

I'm sorry, i'm having a little hard time understanding how I should have it setup then :(

Do you mind put in the missing pieces of how it should be in my Button_Click code below?

Also, I do not have the submit button assigned CausesValidation attribute set to anything. Below is the HTML for my Button Control.

protected void btnSubmitApplication_Click(object sender, EventArgs e)
    {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TMF"].ConnectionString))
            {
                SqlCommand cmdCurrentlyReceive = new SqlCommand();
                cmdCurrentlyReceive.CommandText = "InsertCandidateCurrentlyReceive";
                cmdCurrentlyReceive.CommandType = CommandType.StoredProcedure;
                cmdCurrentlyReceive.Connection = conn;

                SqlCommand cmdFinancialAssistance = new SqlCommand();
                cmdFinancialAssistance.CommandText = "InsertFinancialAssistance";
                cmdFinancialAssistance.CommandType = CommandType.StoredProcedure;
                cmdFinancialAssistance.Connection = conn;

                SqlCommand cmdExtenuating = new SqlCommand();
                cmdExtenuating.CommandText = "InsertExtenuating";
                cmdExtenuating.CommandType = CommandType.StoredProcedure;
                cmdExtenuating.Connection = conn;

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "InsertCandidate";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = conn;

                cmd.Parameters.Add("@state_id", SqlDbType.Int).Value = ddlState.SelectedValue;
                cmd.Parameters.Add("@city_id", SqlDbType.Int).Value = ddlCity.SelectedValue;
                cmd.Parameters.Add("@zip_id", SqlDbType.Int).Value = ddlZipCode.SelectedValue;
                cmd.Parameters.Add("@sch_id", SqlDbType.Int).Value = ddlSchool.SelectedValue;
                cmd.Parameters.Add("@grade_id", SqlDbType.Int).Value = ddlGrade.SelectedValue;
                cmd.Parameters.Add("@age_id", SqlDbType.Int).Value = ddlAge.SelectedValue;
                cmd.Parameters.Add("@hau_id", SqlDbType.Int).Value = ddlHearAboutUs.SelectedValue;
                cmd.Parameters.Add("@c_fname", SqlDbType.VarChar).Value = txtFirstName.Text;
                cmd.Parameters.Add("@c_lname", SqlDbType.VarChar).Value = txtLastName.Text;
                cmd.Parameters.Add("@c_address", SqlDbType.VarChar).Value = txtAddress.Text;
                cmd.Parameters.Add("@c_phone", SqlDbType.VarChar).Value = txtPhone.Text;
                cmd.Parameters.Add("@c_email", SqlDbType.VarChar).Value = txtEmail.Text;
                cmd.Parameters.Add("@c_purpose_desc", SqlDbType.VarChar).Value = txtPurposeApp.Text;
                cmd.Parameters.Add("@c_crname", SqlDbType.VarChar).Value = txtCurrentlyReceiveOtherInfo.Text;
                cmd.Parameters.Add("@c_amount_requested", SqlDbType.VarChar).Value = txtAmountRequested.Text;
                cmd.Parameters.Add("@c_extenuating_desc", SqlDbType.VarChar).Value = txtExtenuatingDesc.Text;
                cmd.Parameters.Add("@c_parentguardian_name", SqlDbType.VarChar).Value = txtParentGuardianFirstLastName.Text;

                try
                {
                    conn.Open();

                    int c_id = Convert.ToInt32(cmd.ExecuteScalar());

                    cmdCurrentlyReceive.Parameters.Add("@c_id", SqlDbType.Int).Value = c_id;
                    cmdCurrentlyReceive.Parameters.Add("@cr_id", SqlDbType.Int);

                    foreach (ListItem item in cblCurrentlyReceiveValues.Items)
                    {
                        if (item.Selected)
                        {
                            cmdCurrentlyReceive.Parameters["@cr_id"].Value = item.Value;
                            cmdCurrentlyReceive.ExecuteNonQuery();
                        }
                    }

                    cmdFinancialAssistance.Parameters.Add("@c_id", SqlDbType.Int).Value = c_id;
                    cmdFinancialAssistance.Parameters.Add("@fa_id", SqlDbType.Int);

                    foreach (ListItem item in cblFinancialAssistanceValues.Items)
                    {
                        if (item.Selected)
                        {
                            cmdFinancialAssistance.Parameters["@fa_id"].Value = item.Value;
                            cmdFinancialAssistance.ExecuteNonQuery();
                        }
                    }

                    cmdExtenuating.Parameters.Add("@c_id", SqlDbType.Int).Value = c_id;
                    cmdExtenuating.Parameters.Add("@ex_id", SqlDbType.Int);

                    foreach (ListItem item in cblExtenuating.Items)
                    {
                        if (item.Selected)
                        {
                            cmdExtenuating.Parameters["@ex_id"].Value = item.Value;
                            cmdExtenuating.ExecuteNonQuery();
                        }
                    }

                    btnSubmitApplication.Enabled = false;

                    SendEmail();
                    Response.Redirect("success.aspx");
                }

                catch (Exception ex)
                {
                    Response.Write(ex);
                    btnSubmitApplication.Enabled = true;
                }
            }
    }

Open in new window


<asp:Button ID="btnSubmitApplication" runat="server" OnClick="btnSubmitApplication_Click" CssClass="button" Text="Submit" />
Avatar of Brian

ASKER

Also, I do prefer Client Side validation over Server Side validation but I had an issue with a user who somehow was able to insert just their FirstName and LastName out of 10 other fields that had the ASP.NET Required Field Validation assigned. They were using an iPhone 4. So I thought it would also be best to have Server Side Validation setup as a backup in the event if somehow JavaScript was disabled on the clients device. Does that make any sense?
ASKER CERTIFIED SOLUTION
Avatar of Paul Jackson
Paul Jackson
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Brian

ASKER

THANK YOU!!! I truly appreciated both examples that you supplied and more importantly the reason as to why it's implemented.

Thanks again!!