ASP.NET

[ASP.NET] Web Form - <asp:TextBox>

yerica 2025. 3. 7. 10:03
  • " 목차 "

 

 

ASP.NET Web Form : TextBox

✅  ASP.NET Web Form의 TextBox란?

 

ASP.NET Web Form에서 <asp:TextBox>는
사용자가 입력할 수 있는 텍스트 필드를 생성하는 서버 컨트롤이다.

이 컨트롤은 HTML의 <input>과 유사하지만,
서버 측에서 관리할 수 있으며 다양한 속성과 이벤트를 지원한다.

 

기본형
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

<!-- 실행 결과 --> 
<input type="text">
기본형태로 작성할 경우 렌더링시 text 타입의 input으로 변환된다.

 

 

 

ASP.NET Web Form : TextBox

01. 주요 속성

  속성 설명
  ID 컨트롤을 식별하는 고유한 이름
  runat="server" 서버 컨트롤임을 지정
  Text 텍스트 박스의 기본값
  TextMode 입력 유형 지정
  Enabled 입력 가능 여부 ( true / false )
     Enable="false"의 경우 완전히 비활성화 되며, 값 전송도 불가능하다.
  ReadOnly 읽기 전용 여부 ( true / false )
     ReadOnly="true"의 경우 사용자는 변경할 수 없지만, 서버로 값이 전송된다.
  MaxLength 최대 입력 가능한 문자 수
  CssClass CSS 스타일 적용
예제
<asp:TextBox ID="txtEmail" runat="server" Text="example@email.com" 
    TextMode="Email" MaxLength="50" CssClass="form-control"></asp:TextBox>
    
<!-- 실행 결과 --> 
<input type="email" name="txtEmail" id="txtEmail" class="form-control" 
       value="example@email.com" maxlength="50">
TextMode 가 email 이기 때문에 변환된 HTML에서 type="email"로 표시된다.
ID를 txtEamil로 설정하면 ASP.NET이 내부적으로 동일한 값으로 name 속성을 자동으로 설정하여 서버에서 값을 읽을 수 있도록한다.
Text 는 TextBox의 기본값으로 입력 필드에 example@email.com이 기본적으로 표시된다.
MaxLength 는 최대 입력 가능한 문자 수로, 위의 예제에선 50자 까지만 입력할 수 있다.

 

- TextMode 속성 (입력 유형 지정)

TextMode 속성을 사용하면 다양한 입력 방식을 설정할 수 있다.

  출력 결과 설명
  SingleLine <input type="text" /> 기본값. 한 줄 입력
  MultiLine <textarea></textarea> 여러줄 입력 가능 (Rows 속성 사용 가능)
  Password <input type="password" /> 입력값이 *** 형태로 마스킹됨
  Email <input type="email" /> 이메일 입력용
  Number <input type="number" /> 숫자 입력용
  Date <input type="date" /> 날짜 입력용
  Time <input type="time" /> 시간 입력용
예시
<asp:TextBox ID="txtComment" runat="server" TextMode="MultiLine" Rows="5" 
    CssClass="form-control"></asp:TextBox>

<!-- 실행 결과 -->
<textarea name="txtComment" id="txtComment" class="form-control" rows="5">Hello</textarea>

 

 

 

 

ASP.NET Web Form : TextBox

02. 서버 측 이벤트

서버에서 실행되는 이벤트(Server-Side Events)로, AutoPostBack="true"를 설정해야 즉시 실행된다.

하지만 AutoPostBack은 남용할 경우 성능이 저하될 수 있으니, 즉시 반응이 필요한 경우에만 사용하는 것을 권장한다.

  이벤트 설명
  TextChanged 사용자가 입력을 변경하고 포커스를 잃을 때 실행된다.
  OnInit 컨트롤이 초기화 될 때 실행된다.
  OnLoad 컨트롤 페이지에 로드될 때 실행된다.
  OnPreReder 페이지가 렌더링 되기 직전에 실행된다.
예시
<asp:TextBox ID="txtName" runat="server" AutoPostBack="true" 
    OnTextChanged="txtName_TextChanged"></asp:TextBox>
<asp:Label ID="lblMessage" runat="server"></asp:Label>

<!-- C# (Code-Behind)
protected void txtName_TextChanged(object sender, EventArgs e)
{
    lblMessage.Text = "입력한 값: " + txtName.Text;
}
-->
사용자가 입력한 후 다른 곳을 클릭하면 서버로 값이 전송되는 코드이다.
AutoPostBack="true" 설정이 없으면 서버로 값이 전송되지 않는다.

 

 

 

ASP.NET Web Form : TextBox

03. 클라이언트 측 이벤트

HTML <input> 요소와 동일하게 클라이언트 측 이벤트(JavaScript / jQuery)를 사용할 수 있다.

onchange, onkeyup, onclick 등등

예시
<asp:TextBox ID="txtEmail" runat="server" onkeyup="validateEmail(this)"></asp:TextBox>
<asp:Label ID="lblError" runat="server" ForeColor="Red"></asp:Label>

<script>
function validateEmail(txt) {
    let emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    let lblError = document.getElementById('<%= lblError.ClientID %>');
    
    if (!emailPattern.test(txt.value)) {
        lblError.innerText = "잘못된 이메일 형식입니다!";
    } else {
        lblError.innerText = "";
    }
}
</script>
사용자가 이메일을 입력하는 동안 onkeyup 이벤트로 즉시 검증한다.

 

 

 

ASP.NET Web Form : TextBox

04. 서버 측 + 클라이언트 측 이벤트 함께 사용하기

ASP.NET에서는 OnTextChangedonchange를 동시에 사용할 수 있다.

서버 이벤트는 페이지 리로드가 발생하지만, 클라이언트 이벤트는 즉각적인 피드백이 가능하다.

예로, 빠른 입력 검사는 JavaScript로 처리하고 서버에는 최종 데이터를 전송하는 식과 같이

서버와 클라이언트를 조합하여 활용하면 더 강력한 기능이 구현된다.

예시
<asp:TextBox ID="txtAge" runat="server" AutoPostBack="true" 
    OnTextChanged="txtAge_TextChanged" onchange="validateAge(this)"></asp:TextBox>
<asp:Label ID="lblAgeMessage" runat="server"></asp:Label>

<script>
function validateAge(txt) {
    if (parseInt(txt.value) < 18) {
        alert("18세 이상만 입력할 수 있습니다.");
        txt.value = "";
    }
}
</script>
<!-- C# (Code-Behind)
protected void txtAge_TextChanged(object sender, EventArgs e)
{
    lblAgeMessage.Text = "입력된 나이: " + txtAge.Text;
}
-->
클라이언트에서 먼저 validateAge로 나이를 검증한 후, 서버에서 TextChanged 이벤트로 값을 처리한다.

 

 

 

ASP.NET Web Form : TextBox

05. 유효성 검사 (Validation)

ASP.NET 에서는 RequiedFieldValidator  같은 유효성 검사 컨트롤을 사용해 필수 입력을 검증할 수 있다.

예시
<asp:TextBox ID="txtPhoneNumber" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPhone" runat="server" 
    ControlToValidate="txtPhoneNumber" ErrorMessage="전화번호를 입력하세요!" 
    ForeColor="Red"></asp:RequiredFieldValidator>

 

 

 

ASP.NET Web Form : TextBox

06. 데이터 바인딩

TextBox는 데이터베이스 값과 바인딩 할 수도 있다.

예시
<asp:TextBox ID="txtUser" runat="server" Text='<%# Eval("UserName") %>'></asp:TextBox>

<script>
	let myTextBox = document.getElementById('<%= txtEmail.ClientID %>');
</script>
위 코드는 데이터 바인딩을 이용해 UserName 필드 값을 TextBox에 표시하도록했다.
TextBox에 자바스크립트 추가 시 <%= ClientID %> 를 사용하면 안정적인 선택도 가능하다.