I have an ASP.Net MVC 3 web application and I am adding a check box to a view page using the HtmlHelper class, like this...
@Html.CheckBox("CheckBox1", true, new { @class = "Class1" })
What I want to do is conditionally add the disabled attribute based on a view state property. Basically the following would be ideal...
@Html.CheckBox("CheckBox1", true, new { @class = "Class1", @disabled = Model.ReadOnly })
Unfortunately, due to the nature of the disabled attribute, this will not work because any value assigned to the disabled attribute (even "false") will be translated as true.
I have already thought of a few solutions to get round this problem, so the question is not how can I do this. But rather, is there a simple way like the desired method above? or do I have to resort to one of the following?..
What I know I could do...
Create an if/else statement and write to different Html.CheckBox
lines (not great for readability - and possible with throw a mark-up warning - not sure)
Skip the HtmlHelper class and hand write the tag allowing for better conditionally attributes (keeps the code shorter, but adds inconsistency)
Create a custom helper that takes a "disabled" parameter (the cleanest solution, but requires undesired extra methods - probably the best option so far though)
Define this somewhere in your view/helpers
@functions { object getHtmlAttributes (bool ReadOnly, string CssClass) { if (ReadOnly) { return new { @class = CssClass, @readonly = "readonly" }; } return new { @class = CssClass }; } }
Then use :
@Html.TextBox("name", "value", @getHtmlAttributes(Model.ReadOnly, "test"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With