Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

asp.net mvc - MVC 3: Conditionally Adding the Disabled Attribute with the HtmlHelpers

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...

  1. 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)

  2. Skip the HtmlHelper class and hand write the tag allowing for better conditionally attributes (keeps the code shorter, but adds inconsistency)

  3. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...