Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.TextBox conditional attribute with ASP.NET MVC Preview 5

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?

like image 306
tags2k Avatar asked Oct 07 '08 08:10

tags2k


1 Answers

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" } 
like image 57
Panos Avatar answered Sep 17 '22 16:09

Panos