MVC 3:有条件地添加与HtmlHelpers残疾人属性 [英] MVC 3: Conditionally Adding the Disabled Attribute with the HtmlHelpers
问题描述
我有一个ASP.Net MVC 3 Web应用程序,我使用的是HtmlHelper类添加一个复选框视图页面,这样的...
@ Html.CheckBox(CheckBox1,真正的,新的{@class =1级})
我想这样做是有条件添加基于视图状态属性disabled属性是什么。基本上,下面将是理想...
@ Html.CheckBox(CheckBox1,真正的,新的{@class =1级,@disabled = Model.ReadOnly})
不幸的是,由于残疾人属性的性质,这是行不通的,因为的任何的分配给残疾人属性(甚至是假)值将被翻译成真实的。
我已经想到了一些解决方案来克服这个问题,所以问题不在于我怎么能做到这一点。而是有没有像上面所期望的方法一个简单的方法?还是我不得不求助于以下步骤之一?..
我知道,我能做的......
-
创建一个if / else语句,并写入不同的
Html.CheckBox
行(不是很大的可读性 - 和可能的抛出一个标记警示 - 不能确定) -
跳过HtmlHelper类和手写标签,允许有条件更好的属性(保持code较短,但增加了不一致)
-
创建一个自定义助手,需要一个禁用参数(干净的解决方案,但需要额外的不需要的方法 - 可能是最好的选择,到目前为止虽然)
在您的视图/助手定义这个地方
@functions {
对象getHtmlAttributes(布尔只读,字符串的CssClass)
{
如果(只读){
返回新{@class =的CssClass,@ReadOnly =只读};
}
返回新{@class =的CssClass};
}
}
然后使用:
@ Html.TextBox(名,价值,@getHtmlAttributes(Model.ReadOnly,测试))
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"))
这篇关于MVC 3:有条件地添加与HtmlHelpers残疾人属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!