Why Data is not posted in asp.net using postback?

Total Post:51

Points:359
C#  ASP.Net 
 995  View(s)
Ratings:
Rate this:
I'm trying to post data to the same page after postback with the help of ViewState. I fill out the contents of the page and post the form and display the input on the same page but the validator says that the firstname cannot be null while I just filled out the textbox before I submitted the form.
<asp:Content ContentPlaceHolderID="Main" runat="server" EnableViewState="true">
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    <asp:Label ID="lbl1" Text="First Name" runat="server" />
                </td>
                <td>
 
                <asp:TextBox ID="tFirstName" runat="server" />
            </td>
            <td>
                <asp:RequiredFieldValidator ControlToValidate="tFirstName" ErrorMessage="This field cannot be empty."
                    runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lbl2" Text="Last Name" runat="server" />
            </td>
            <td>
                <asp:TextBox ID="tLastName" runat="server" />
            </td>
        </tr>           
    </table>
</div>
<asp:Button ID="id" Text="Submit" runat="server" OnClick="Submit" />
<div>
    <p>
        <asp:Label ID="lTest" runat="server" /></p>
</div>
<asp:Label ID="lSubmit" runat="server" />
</form>


.cs code:

protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                tFirstName.Text = (string)ViewState["tFirstName"];
                tLastName.Text = (string)ViewState["tLastName"];
            }
            else
            {
                ViewState["tFirstName"] = tFirstName.Text;
                ViewState["tLastName"] = tLastName.Text;
            }
        }
 
        protected void Submit(object sender, System.EventArgs args)
        {
            try
            {
                lTest.Text = tFirstName.Text + " " tLastName.Text;
            }
            catch (Exception ex)
            {
 
                throw;
            }
        }

  1. Post:194

    Points:1396
    Re: Why Data is not posted in asp.net using postback?

    try this code:

    if (!Page.IsPostBack)
    {
         tFirstName.Text = (string)ViewState["tFirstName"];
         tLastName.Text = (string)ViewState["tLastName"];
    }

      Modified On Apr-05-2018 06:35:44 AM

Answer