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)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…