vote up 3 vote down
star

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?

offensive?
add comment

3 Answers:

vote up 3 vote down
check

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" }
link|offensive?
add comment
vote up 3 vote down

And alternative is just to emit it as plain old HTML. Yes, the editor will make you think you are wrong, but that seems to happen quite frequently with VS2008SP1. This example is specifically for checkboxes which seems to be completely wasted in CTP5, but it gives you an idea how to emit conditional attributes.

<input type="checkbox" name="roles" value='<%# Eval("Name") %>' 
  <%# ((bool) Eval("InRole")) ? "checked" : "" %> 
  <%# ViewData.Model.IsInRole("Admin") ? "" : "disabled" %> />
link|offensive?
add comment
vote up 0 vote down

I think it should be

<%= ((bool) Eval("InRole")) ? "checked" : "" %>

instead of this in leppies answer.

<%# ((bool) Eval("InRole")) ? "checked" : "" %>

At least it did not work for me with # but it worked with =. Did i do anything wrong? Thanks for the tip anyway :)

link|offensive?
add comment

Your Answer:

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.