Search code examples
c#asp.netformswebformsserver-side

Value/Text reurns null in Server side controls if I kept outside of the form but with body


I am using server side controls in web form application. In this i am appending my HTML elements and server side elements out side of the form (asp:content) but its appending to body of that page. In server side (in button click) the value/ text of the controls return null. Is there any specific reason for this for returning null when control kept outside of the asp:content tag.

I know its may its not kept inside the form but why i am not posting just taking the values in server side event for further process Thanks for any suggestion Here below i have added the textbox to a page.Later via script i will append to body tag. now while checking the server side its return null

 <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckboxIssue._Default" %>


   <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>


 <script>
         $("#MainContent_TextBox2").appendTo("body");

  </script>

}

server side

    protected void btn_Click(object sender, EventArgs e)
    {
        var text1 = TextBox1.Text;
    }

Solution

  • They called it WebForms for a reason. The concept is to keep server controls inside a form and post it back all the times on an ui event with a server side handler. So you have to follow that rule if you are using webforms.

    You may get the controls placed outside a form rendered, but aspx engine won't pick their values on the postback.