2008-10-07 66 views
27

我有一个强类型的MVC视图控件,它负责用户可以在其中创建和编辑客户端项目的UI。我希望他们能够在创建时定义ClientId,但不能编辑,并且这将在UI中反映出来。ASP.NET MVC的Html.TextBox条件属性预览5

为此,我有以下行:

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

看来,无论什么价值我给只读属性(甚至是“假”和“”),Firefox和IE7使输入读取 - 只是,这是令人讨厌的反直觉。如果不需要,可以使用完全基于三元运算符的方法完全删除属性吗?

回答

35

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

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

如果要定义多个属性,那么你必须定义两个匿名类型和有多个属性的副本。例如,这样的事情(我不喜欢反正):

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

+1我的第一个镜头是没有投反对的第二代码片段。它容易被忽视,但真正必要。 – 2012-06-18 15:55:32

4

和替代仅仅是发射为普通的老HTML。是的,编辑会让你认为你错了,但是VS2008SP1似乎经常发生这种情况。这个例子专门用于复选框,它似乎完全被CTP5浪费掉了,但是它给了你如何发出条件属性的想法。

<input type="checkbox" name="roles" value='<%# Eval("Name") %>' 
    <%# ((bool) Eval("InRole")) ? "checked" : "" %> 
    <%# ViewData.Model.IsInRole("Admin") ? "" : "disabled" %> /> 
1

我觉得应该是

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

,而不是这leppies回答。

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

至少它没有为我工作#但它与=一起工作。我做错了什么吗?感谢您的提示:)

0
$(function(){$(“[readonly ='false']”)。removeAttr(“readonly”); });
21

如果要定义几个属性和条件只读不复制其他属性, 你可以使用字典而不是匿名类型的属性。

例如

Dictionary<string, object> htmlAttributes = new Dictionary<string, object>(); 
htmlAttributes.Add("class", "myCSS"); 
htmlAttributes.Add("data-attr1", "val1"); 
htmlAttributes.Add("data-attr2", "val2"); 
if (Model.LoggedInData.IsAdmin == false) 
{ 
    htmlAttributes.Add("readonly", "readonly"); 
} 


@:User: @Html.TextBoxFor(
    m => m.User, 
    htmlAttributes) 
+1

应该是答案,因为它避免了重复。 – 2013-12-02 17:29:15

-2

我尝试了上面的大部分建议,现在我已经用最简单的方法得出结论。通过声明其中一个为“对象”类型,组合2个匿名html属性对象。

@Html.TextBoxFor(m => m.Email, !isEdit ? new { id = "email_box" } : new { id = "email_box", @readonly = isEdit ? "readonly" : "false" } as object) 
+0

这对我不起作用; `@readonly = false`仍然被解释为'只读' – 2015-10-16 09:16:50

2

提示:它只是存在readonly/disabled属性,使元素在浏览器中只读或禁用。

@Html.TextBoxFor(x => x.Name, isReadonly ?(object) new { @readonly = true } : new { /*Some other attributes*/ }) 
+0

为什么匿名类需要被转换为三态op的第一个条件的对象?不要挑战它,只是试图理解它。谢谢! – eaglei22 2017-06-09 16:42:41

0

我用这个:

@Html.TextAreaFor(model => model.ComentarioGestor, comentarioGestor? new { @class = "form-control" } : new { @class = "form-control", @readonly = "readonly" } as object)