Html.TextBox conditional attribute with ASP.NET MV

2020-02-26 03:24发布

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?

8条回答
▲ chillily
2楼-- · 2020-02-26 03:57

I tried most of the suggestions above and now I have arrived at the simplest with a single line. Combine 2 anonymous html attributes object by declaring wither one of it as "object" type.

@Html.TextBoxFor(m => m.Email, !isEdit ? new { id = "email_box" } : new { id = "email_box", @readonly = isEdit ? "readonly" : "false" } as object)
查看更多
小情绪 Triste *
3楼-- · 2020-02-26 03:59

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 :)

查看更多
登录 后发表回答