Html.TextBoxFor
readonly attribute
ASP.NET MVC
C#
Razor syntax

Can I set text box to readonly when using Html.TextBoxFor?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Yes, you can make a textbox readonly when using Html.TextBoxFor in ASP.NET MVC. The key is passing HTML attributes correctly through the helper overload. Readonly fields are still posted with the form, which is often the right behavior for review screens and protected values.

Basic Readonly Syntax With TextBoxFor

Use the htmlAttributes argument and set the readonly attribute explicitly.

cshtml
1@model UserViewModel
2
3@Html.TextBoxFor(
4    m => m.Email,
5    new {
6        @class = "form-control",
7        @readonly = "readonly"
8    }
9)

This renders an input users can focus and copy from, but cannot edit in the browser.

Conditional Readonly Based on View State

A common pattern is enabling edit for administrators and readonly for others.

cshtml
1@{
2    bool canEdit = User.IsInRole("Admin");
3}
4
5@Html.TextBoxFor(
6    m => m.CustomerId,
7    canEdit
8        ? new { @class = "form-control" }
9        : new { @class = "form-control", @readonly = "readonly" }
10)

Use conditional attributes in the view model layer when possible, so UI logic remains predictable.

Readonly Versus Disabled

readonly and disabled are not equivalent. Disabled fields are not submitted in standard form post, while readonly fields are included.

cshtml
@Html.TextBoxFor(m => m.OrderNumber, new { @disabled = "disabled" })

If server logic depends on posted value, prefer readonly. If you truly want field excluded from post, disabled is acceptable.

Regardless of UI attributes, always validate on server side. Browser level restrictions are not security controls.

Editor Templates and Reuse

If your application has many readonly fields, centralize rendering in an editor template. This avoids duplicated markup and makes style updates easier.

cshtml
@model string
@Html.TextBox("", Model, new { @class = "form-control", @readonly = "readonly" })

Then call template from strongly typed views for consistent behavior across forms.

Model Binding and Security Considerations

Readonly controls improve user experience but are not a security boundary. Attackers can still edit posted values using browser tools or custom requests. Always validate incoming values on the server and ignore client supplied fields that should remain immutable.

In update actions, load protected values from database rather than trusting posted payload.

csharp
1[HttpPost]
2public ActionResult Update(UserViewModel input)
3{
4    var entity = _repo.GetById(input.Id);
5    entity.Email = entity.Email; // keep immutable field from persisted data
6    entity.DisplayName = input.DisplayName;
7
8    _repo.Save(entity);
9    return RedirectToAction("Details", new { id = input.Id });
10}

The line preserving immutable data can be replaced with cleaner mapping rules, but the core idea remains the same.

Building Reusable Html Helpers

If readonly behavior appears across many forms, create a helper extension to standardize markup.

csharp
1public static class HtmlReadonlyExtensions
2{
3    public static IHtmlString ReadonlyTextBoxFor<TModel, TValue>(
4        this HtmlHelper<TModel> html,
5        Expression<Func<TModel, TValue>> expression,
6        object htmlAttributes = null)
7    {
8        var attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes ?? new { });
9        attrs["readonly"] = "readonly";
10        return html.TextBoxFor(expression, attrs);
11    }
12}

Reusable helpers reduce copy paste and keep form behavior consistent.

Common Pitfalls

  • Forgetting @readonly syntax and using reserved keyword without prefix.
  • Assuming readonly protects data integrity without server validation.
  • Using disabled when value is still required on postback.
  • Mixing conditional logic directly in long view markup and hurting readability.
  • Not testing behavior with browser autofill or accessibility tools.

Summary

  • Html.TextBoxFor supports readonly through the htmlAttributes argument.
  • Use @readonly = "readonly" for consistent HTML output.
  • Choose readonly when value should still be submitted.
  • Use disabled only when omission from form post is intended.
  • Keep authorization and data integrity checks on the server.
  • Centralized helper methods reduce duplicate markup and make readonly behavior easier to audit during accessibility and security reviews.
  • Validate server side mapping rules whenever readonly fields represent business critical identifiers or immutable account attributes.
  • Pair readonly fields with clear labels so users understand why editing is blocked and where allowed updates should be made.
  • Add integration tests for postback behavior so readonly fields are submitted exactly as expected in real form workflows.

Course illustration
Course illustration

All Rights Reserved.