Skip to content

Instantly share code, notes, and snippets.

@JudsonMurray
Forked from Scribbio/ReadonlyBool.cshtml
Created October 24, 2025 15:58
Show Gist options
  • Save JudsonMurray/ceaa99f0bc845485120201701fe97c1b to your computer and use it in GitHub Desktop.
Save JudsonMurray/ceaa99f0bc845485120201701fe97c1b to your computer and use it in GitHub Desktop.
Linking readonly to a dynamic boolean in Razor
@* We can link the readonly html attribute to a bool defined in Razor code.
This is a neat trick if you want to use the same view for different purposes.
For example, I have an AddProduct page that also acts as the EditProduct page. In "EditProduct" mode, some of the form fields that are
used to add a new product are no longer editable (such as the product name).
This is achieved using the html readonly attribute in the relevant fields set against a single boolean variable "@editMode".
This variable is defined at the top of the page and can be set multiple ways through the controller: ViewBag/ViewModel, etc.
This approach reduces the need for Razor "if" statements and duplicate code. Example code below. *@
@model Gist.Models.Product
@{
bool editMode = ViewBag.IsEdit ?? false;
}
@using (Html.BeginForm("AddProduct", "Home", FormMethod.Post, new { @id = "formAddProduit" }))
{
<div class="row">
<label class="col-md-4 control-label">Product name</label>
<input class="col-md-8" name="ProductName" type="text" value="@(Model.ProductName)" readonly="@editMode" />
</div>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment