带有 ASP.NET MVC Preview 5 的 Html.TextBox 条件属性 [英] Html.TextBox conditional attribute with ASP.NET MVC Preview 5

查看:11
本文介绍了带有 ASP.NET MVC Preview 5 的 Html.TextBox 条件属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个强类型的 MVC 视图控件,它负责用户可以在其中创建和编辑客户端项目的 UI.我希望他们能够在创建时定义 ClientId,但不能编辑,这会反映在 UI 中.

为此,我有以下几行:

<%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId, new{ @readonly =(ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0?只读":假")})%>

似乎无论我给 readonly 属性赋予什么值(甚至是false"和"),Firefox 和 IE7 都会将输入设为只读,这非常违反直觉.如果不需要,是否有一种很好的、​​基于三元运算符的方法来完全删除属性?

解决方案

棘手的问题... 但是,如果你只想定义 readonly 属性,你可以这样做:

p>

<%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId,ViewData.Model.ClientId != null &&ViewData.Model.ClientId.Length >0?新的 { @readonly = "只读" }: 空值)%>

如果要定义更多属性,则必须定义两个匿名类型并拥有多个属性副本.例如,像这样的东西(反正我不喜欢):

ClientId.Length >0?(object)new { @readonly = "readonly", @class = "myCSS" }: (object)new { @class = "myCSS" }

I have a strongly-typed MVC View Control which is responsible for the UI where users can create and edit Client items. I'd like them to be able to define the ClientId on creation, but not edit, and this to be reflected in the UI.

To this end, I have the following line:

<%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId, new 
 { @readonly = 
   (ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0 
      ? "readonly" : "false") 
 } )
%>

It seems that no matter what value I give the readonly attribute (even "false" and ""), Firefox and IE7 make the input read-only, which is annoyingly counter-intuitive. Is there a nice, ternary-operator-based way to drop the attribute completely if it is not required?

解决方案

Tough problem... However, if you want to define only the readonly attribute, you can do it like this:

<%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId, 
  ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0 
    ? new { @readonly =  "readonly" } 
    : null) 
%>

If you want to define more attributes then you must define two anonymous types and have multiple copies of the attributes. For example, something like this (which I don't like anyway):

ClientId.Length > 0 
  ? (object)new { @readonly = "readonly", @class = "myCSS" } 
  : (object)new { @class = "myCSS" }

这篇关于带有 ASP.NET MVC Preview 5 的 Html.TextBox 条件属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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