MVC 3:有条件地添加与HtmlHelpers残疾人属性 [英] MVC 3: Conditionally Adding the Disabled Attribute with the HtmlHelpers

查看:131
本文介绍了MVC 3:有条件地添加与HtmlHelpers残疾人属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.Net MVC 3 Web应用程序,我使用的是HtmlHelper类添加一个复选框视图页面,这样的...

  @ Html.CheckBox(CheckBox1,真正的,新的{@class =1级})

我想这样做是有条件添加基于视图状态属性disabled属性是什么。基本上,下面将是理想...

  @ Html.CheckBox(CheckBox1,真正的,新的{@class =1级,@disabled = Model.ReadOnly})

不幸的是,由于残疾人属性的性质,这是行不通的,因为任何分配给残疾人属性(甚至是假)值将被翻译成真实的。

我已经想到了一些解决方案来克服这个问题,所以问题不在于我怎么能做到这一点。而是有没有像上面所期望的方法一个简单的方法?还是我不得不求助于以下步骤之一?..

我知道,我能做的......


  1. 创建一个if / else语句,并写入不同的 Html.CheckBox 行(不是很大的可读性 - 和可能的抛出一个标记警示 - 不能确定)


  2. 跳过HtmlHelper类和手写标签,允许有条件更好的属性(保持code较短,但增加了不一致)


  3. 创建一个自定义助手,需要一个禁用参数(干净的解决方案,但需要额外的不需要的方法 - 可能是最好的选择,到目前为止虽然)



解决方案

在您的视图/助手定义这个地方

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

  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)

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆