当用户向其中输入数据时,TextBox.Text为null

时间:2016-10-14 14:19:24

标签: c# asp.net

我尝试恢复用户输入文本框的内容。

我创建了访问器以使我的文本框公开,因为我之前遇到过可访问性问题。

这里是关于连接的完整aspx.cs:

public partial class ConnexionSaisieHeures : System.Web.UI.Page
{
    /*Accesseurs*/

    public string NomUtilisateur
    {
        get
        {
            return txtNomUtilisateur.Text;
        }
        set
        {
            txtNomUtilisateur.Text = value;
        }
    }

    public string MotDePasse
    {
        get
        {
            return txtMotDePasse.Text;
        }
        set
        {
            txtMotDePasse.Text = value;
        }
    }

    /*Événements*/

    protected void Page_Load(object sender, EventArgs e)
    {
        ErreurConnexion.Visible = false;
        lblErreurConnexion.Text = "";
    }

    protected void btnConnexion_Click(object sender, EventArgs e)
    {
        if (Authentifier(txtNomUtilisateur.Text, txtMotDePasse.Text))
        {
            FormsAuthentication.RedirectFromLoginPage(txtNomUtilisateur.Text, false);
        }
        else
        {
            ErreurConnexion.Visible = true;
            lblErreurConnexion.ForeColor = System.Drawing.Color.Red;
            lblErreurConnexion.Text = "Erreur d'authentification : Le nom d'utilisateur ou le mot de passe est incorrect.";
        }
    }

    /*Méthodes*/

    /// <summary>
    /// Méthode permettant l'authentification des utilisateurs à l'application
    /// </summary>
    /// <param name="strNomUtilisateur">Nom de l'utilisateur saisi</param>
    /// <param name="strMotDePasse">Mot de passe saisi</param>
    /// <returns>Booléen vérifiant si l'authentification a été faite ou non</returns>

    private bool Authentifier(string strNomUtilisateur, string strMotDePasse)
    {
        bool bOk = false;
        // Cryptage du mot de passe
        strMotDePasse = FormsAuthentication.HashPasswordForStoringInConfigFile(strMotDePasse, "MD5");
        // Création d'une connexion SGBD
        SqlConnection oConnexion = new SqlConnection(Convert.ToString(ConfigurationManager.ConnectionStrings["SaisieHeuresConnectionString"]));
        // Définition de la requête à exécuter
        SqlCommand oCommand = new SqlCommand("SELECT * FROM Utilisateurs WHERE NomUtilisateur='" + strNomUtilisateur + "'", oConnexion);
        try
        {
            // Ouverture de la connexion et exécution de la requête
            oConnexion.Open();
            SqlDataReader drUtilisateur = oCommand.ExecuteReader();
            // Parcours de la liste des utilisateurs
            while (drUtilisateur.Read())
            {
                if (drUtilisateur["MotDePasse"].ToString() == strMotDePasse)
                {
                    bOk = true;
                    break;
                }
            }
        }
        catch
        {
            bOk = false;
        }
        oConnexion.Close();
        return bOk;
    }
}

这里是第二个表单上的部分,由于用户名和密码而拥有用户的名字和姓氏:

private static ConnexionSaisieHeures WebFormConnexionSaisieHeures = new ConnexionSaisieHeures();

private void PrenomNomUtilisateur()
        {
            SqlConnection oConnexion = new SqlConnection(Convert.ToString(ConfigurationManager.ConnectionStrings["SaisieHeuresConnectionString"]));
            SqlCommand oCommand = new SqlCommand("SELECT * FROM Utilisateurs WHERE NomUtilisateur='" + WebFormConnexionSaisieHeures.NomUtilisateur + "'", oConnexion);

            try
            {
                // Ouverture de la connexion et exécution de la requête
                oConnexion.Open();
                SqlDataReader drUtilisateur = oCommand.ExecuteReader();
                // Parcours de la liste des utilisateurs
                while (drUtilisateur.Read())
                {
                    if (drUtilisateur["MotDePasse"].ToString() == WebFormConnexionSaisieHeures.MotDePasse)
                    {
                        PrenomNom = drUtilisateur["PrenomNom"].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception : " + ex.Message);
            }
            oConnexion.Close();
        }

我的第一个webform的aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ConnexionSaisieHeures.aspx.cs" Inherits="SaisieHeures.ConnexionSaisieHeures" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>WEATHER MEASURES : Connexion à l'application de saisie des heures</title>
    <link href="SaisieHeures.css" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" />
</head>

<body>
    <header>
        Saisie des heures - Connexion
    </header>

    <br />

    <article>
        <form id="FormConnexionSaisieHeures" runat="server">
            <table id="ErreurConnexion" runat="server">
                <tr>
                    <td>
                        <asp:Label ID="lblErreurConnexion" runat="server" ForeColor="Red"></asp:Label>
                    </td>
                </tr>
            </table>
            <br />
            <table id="Connexion">
                <tr>
                    <td>
                        <asp:Label ID="lblNomUtilisateur" runat="server" Text="Nom d'utilisateur :"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="txtNomUtilisateur" runat="server" Style="text-align: center"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="lblMotDePasse" runat="server" Text="Mot de passe :"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="txtMotDePasse" runat="server" TextMode="Password" Style="text-align: center"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Button ID="btnConnexion" runat="server" Text="Connexion" OnClick="btnConnexion_Click" />
                    </td>
                </tr>
            </table>
        </form>
    </article>
</body>
</html>

我的第二个webform的aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SaisieHeures.aspx.cs" Inherits="SaisieHeures.SaisieHeures" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>WEATHER MEASURES : Application de saisie des heures</title>
    <link href="SaisieHeures.css" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" />
</head>

<body>
    <header>
        Saisie des heures - Application
    </header>

    <br />

    <article>
        <form id="FormSaisieHeures" runat="server">
            <table id="PrenomNomUtilisateur">
                <tr>
                    <td colspan="2">
                        <asp:Label ID="lblPrenomNomUtilisateur" runat="server"></asp:Label>
                    </td>
                </tr>
            </table>
            <br />
            <table id="SelectionMoisAnnee">
                <tr>
                    <td>
                        <asp:Button ID="btnMoisPrecedent" runat="server" Text="<" OnClick="btnMoisPrecedent_Click" />
                        <asp:Label ID="lblMoisAnnee" runat="server"></asp:Label>
                        <asp:Button ID="btnMoisSuivant" runat="server" Text=">" OnClick="btnMoisSuivant_Click" />
                    </td>
                </tr>
            </table>
            <br />
            <table id="ErreurSaisie" runat="server">
                <tr>
                    <td>
                        <asp:Label ID="lblErreurSaisie" runat="server"></asp:Label>
                    </td>
                </tr>
            </table>
            <br />
            <table id="FicheSaisieHeures">
                <tr>
                    <td>
                        <asp:Label ID="lblChoixSemaine" runat="server" Text="Semaine : "></asp:Label>
                    </td>
                    <td>
                        <asp:DropDownList ID="ddlSemaines" runat="server" OnSelectedIndexChanged="ddlSemaines_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="lblJours" runat="server" Text="Jours de la semaine"></asp:Label>
                    </td>
                    <td>
                        <asp:Label ID="lblNombreHeuresRealise" runat="server" Text="Nombre d'heures réalisées"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="lblLundi" runat="server"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="txtHeuresLundi" runat="server" Style="text-align: center"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="lblMardi" runat="server"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="txtHeuresMardi" runat="server" Style="text-align: center"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="lblMercredi" runat="server"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="txtHeuresMercredi" runat="server" Style="text-align: center"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="lblJeudi" runat="server"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="txtHeuresJeudi" runat="server" Style="text-align: center"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="lblVendredi" runat="server"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="txtHeuresVendredi" runat="server" Style="text-align: center"></asp:TextBox>
                    </td>
                </tr>
            </table>
            <br />
            <table id="MessagesCalculTotalHeuresMois" runat="server">
                <tr>
                    <td>
                        <asp:Label ID="lblMessageCalculTotalHeuresMois" runat="server"></asp:Label>
                    </td>
                </tr>
            </table>
            <br />
            <table id="TotalHeuresMois">
                <tr>
                    <td>
                        <asp:Label ID="lblTotalHeuresMois" runat="server" Text="Nombre total d'heures réalisées dans le mois"></asp:Label>
                        <br />
                        <asp:TextBox ID="txtCalculTotalHeuresMois" runat="server" ReadOnly="True" Style="text-align: center"></asp:TextBox>
                    </td>
                </tr>
            </table>
            <br />
            <table id="Boutons">
                <tr>
                    <td>
                        <asp:Button ID="btnValider" runat="server" Text="Valider" OnClick="btnValider_Click" />
                    </td>
                    <td>
                        <asp:Button ID="btnAnnuler" runat="server" Text="Annuler" OnClick="btnAnnuler_Click" />
                    </td>
                    <td>
                        <asp:Button ID="btnGenererExcel" runat="server" Text="Générer Excel" OnClick="btnGenererExcel_Click" />
                    </td>
                    <td>
                        <asp:Button ID="btnDeconnexion" runat="server" Text="Déconnexion" OnClick="btnDeconnexion_Click" />
                    </td>
                </tr>
            </table>
        </form>
    </article>
</body>
</html>

txtNomUtilisateur.Textnull;它永远不会恢复用户输入的文本。

我该如何解决呢?

(First Reedit的完整代码,我可以获得你需要的更多信息,我真的想解决它)

P.S。 :@ElekGuidolin我在您的命题之前重新输入原始代码,以向您展示我最初做过的事情。

1 个答案:

答案 0 :(得分:1)

克里斯托弗。 对此感到抱歉。但实际上我想改进答案以更好的方式来解释这一点。

当您使用Asp.Net Web窗体时,您可以使用或不使用Request.Form获取文本框的值,但仅在回发后。 如果你想从Request.Form获取值,你需要在引号内加上字段的整个名称,如果是asp.Net控件,它将是这样的:ctl00 $ FeaturedContent $ txtMyTest 。 但是你也可以像你最初发布的那样获得价值。

所以,两种方式都有效,但只有在回发之后,好吗?

如果您在考虑输入标签时会一起改变,那么您正在谈论客户端脚本。 这是另一个帖子和另一个主题的问题,对吧?!

public string TestProperty
{
    get
    {
        //return txtMyTest.Text;
        return Request.Form["ctl00$FeaturedContent$txtMyTest"];
    }
    set
    {
        txtMyTest.Text = value;
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        lblMyTest.Text = TestProperty;
    }
}

编辑:
@ChristopherLEBAS,因为当你在第二个Form中创建一个新的ConnexionSaisieHeures时,第二个中的值将始终为null,因为你正在创建它们(私有静态ConnexionSaisieHeures WebFormConnexionSaisieHeures = new ConnexionSaisieHeures();),而不是使用现存的填写表格。

由于您希望在其他页面中包含此信息,可能更好的方法是使用会话或Cookie,因为您需要维护页面之间的状态,因此您可以执行以下操作:

protected void btnConnexion_Click(object sender, EventArgs e)
{
    Session["NomUtilisateur"] = txtNomUtilisateur.Text;
    Session["MotDePasse"] = FormsAuthentication.HashPasswordForStoringInConfigFile(txtMotDePasse.Text, "MD5");

    if (Authentifier(txtNomUtilisateur.Text, txtMotDePasse.Text))
    {
        FormsAuthentication.RedirectFromLoginPage(txtNomUtilisateur.Text, false);
    }
    else
    {
        ErreurConnexion.Visible = true;
        lblErreurConnexion.ForeColor = System.Drawing.Color.Red;
        lblErreurConnexion.Text = "Erreur d'authentification : Le nom d'utilisateur ou le mot de passe est incorrect.";
    }
}

然后,在第二种形式:

private void PrenomNomUtilisateur()
{
    string _NomUtilisateur = Session["NomUtilisateur"];
    string _MotDePasse = Session["MotDePasse"];
    SqlConnection oConnexion = new SqlConnection(Convert.ToString(ConfigurationManager.ConnectionStrings["SaisieHeuresConnectionString"]));
    SqlCommand oCommand = new SqlCommand("SELECT * FROM Utilisateurs WHERE NomUtilisateur='" + _NomUtilisateur + "'", oConnexion);

    try
    {
        // Ouverture de la connexion et exécution de la requête
        oConnexion.Open();
        SqlDataReader drUtilisateur = oCommand.ExecuteReader();
        // Parcours de la liste des utilisateurs
        while (drUtilisateur.Read())
        {
            if (drUtilisateur["MotDePasse"].ToString() == _MotDePasse)
            {
                PrenomNom = drUtilisateur["PrenomNom"].ToString();
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception : " + ex.Message);
    }
    finally
    {
        oConnexion.Close();
    }
}

请注意,我放置了一个Finally块,因为如果发生某些错误,连接仍将关闭。