Home > DeveloperSection > Forums > Why Data is not posted in asp.net using postback?
Hugh Jackman
Hugh Jackman

Total Post:52

Points:366
Posted on    October-05-2014 11:49 PM

 ASP.Net ASP.Net  C# 
Ratings:


 1 Reply(s)
 497  View(s)
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;

            }

        }



Kamlakar Singh
Kamlakar Singh

Total Post:194

Points:1396
Posted on    October-05-2014 11:53 PM

try this code:
if (!Page.IsPostBack)

{

     tFirstName.Text = (string)ViewState["tFirstName"];

     tLastName.Text = (string)ViewState["tLastName"];

}


Don't want to miss updates? Please click the below button!

Follow MindStick