Home Set property "readonly" for @Html.TextBoxFor( ) dynamically based on fetched information from db
Reply: 1

Set property "readonly" for @Html.TextBoxFor( ) dynamically based on fetched information from db

Shariq Alee
1#
Shariq Alee Published in 2017-11-14 19:30:34Z

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?

Shyju
2#
Shyju Reply to 2017-11-14 19:48:04Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.308808 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO