30

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

为此,我有以下行:

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

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

4

8 回答 8

37

棘手的问题...但是,如果您只想定义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" }
于 2008-10-07T11:29:53.753 回答
31

如果要定义多个属性,并且条件只读而不重复其他属性,则可以使用 Dictionary 而不是匿名类型的属性。

例如

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)  
于 2012-12-11T09:44:29.230 回答
5

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

@Html.TextBoxFor(x => x.Name, isReadonly ?(object) new { @readonly = true } : new { /*Some other attributes*/ })
于 2015-11-23T06:44:20.693 回答
4

另一种方法是将其作为普通的旧 HTML 发出。是的,编辑器会让你认为你错了,但这种情况在 VS2008SP1 中似乎经常发生。此示例专门针对在 CTP5 中似乎完全被浪费的复选框,但它让您了解如何发出条件属性。

<input type="checkbox" name="roles" value='<%# Eval("Name") %>' 
  <%# ((bool) Eval("InRole")) ? "checked" : "" %> 
  <%# ViewData.Model.IsInRole("Admin") ? "" : "disabled" %> />
于 2008-10-07T11:37:32.583 回答
1

我认为应该是

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

而不是这个 leppies 答案。

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

至少它不适用于我,但它适用于 =。我做错什么了吗?无论如何感谢您的提示:)

于 2008-12-04T10:38:49.933 回答
1

我用这个:

   @Html.TextAreaFor(model => model.ComentarioGestor, comentarioGestor? new { @class = "form-control" } : new { @class = "form-control", @readonly = "readonly" } as object)
于 2017-05-09T23:38:57.180 回答
0
$(function() { $("[readonly='false']").removeAttr("readonly"); });
于 2010-08-09T19:31:36.450 回答
-1

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

@Html.TextBoxFor(m => m.Email, !isEdit ? new { id = "email_box" } : new { id = "email_box", @readonly = isEdit ? "readonly" : "false" } as object)
于 2014-06-05T09:13:00.103 回答