I have multiple Textboxes defined using @Html.TextBoxFor(). Now I want some of them to be only "readonly" and some of them editable, based on the role of user accessing the page.
I have tried using the following
@Html.TextBoxFor(f => f.VSSLabel, new { style = "height:19px", @Value = @ViewBag.fetchf.VSSLabel, @readonly="readonly" })
Is there any way that we can set @readonly="false" and it becomes editable, or any other approach so I switch it to "readonly" and editable based on the Value stored in a ViewBag variable coming from controller?
Unfortunately all the below mark will render a readonly textbox input
<input type="text" name="s1" readonly="readonly"/>
<input type="text" name="s2" readonly="no" />
<input type="text" name="s2" readonly="reallyDoNotWant" />
<input type="text" name="s3" readonly="false" />
<input type="text" name="s4" readonly />
The existence of readonly
attribute makes the input element readonly. Value does not matter.
So you should conditionally render it
if (yourExpressionWhichGivesBooleanValue)
{
@Html.TextBoxFor(a => a.VSSLabel)
}
else
{
@Html.TextBoxFor(a => a.VSSLabel, new { @readonly = "readonly" })
}
If you want to check it against a viewbag dictionary item
if (ViewBag.IsAdmin !=null && ViewBag.IsAdmin)
{
@Html.TextBoxFor(a => a.VSSLabel)
}
else
{
@Html.TextBoxFor(a => a.VSSLabel, new { @readonly = "readonly" })
}
Assuming you are setting ViewBag.IsAdmin
to a boolean value in your action method.