我有一个强类型的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”和“&quot;”),Firefox和IE7都使输入成为只读,这是令人讨厌的反直觉。如果不需要,是否有一个很好的,基于三元运算符的方法来完全删除属性?

有帮助吗?

解决方案

难题......但是,如果您只想定义 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" }

其他提示

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

e.g。

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)  

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

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

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

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

我认为应该是

<%= ((bool) Eval("InRole")) ? "checked" : "" %> 
而不是在leppies回答这个。

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

至少它对我不起作用#但它与=一起工作。我做错了什么吗?无论如何,谢谢你的提示:)

$(function(){   $(&QUOT; [只读= '假']&QUOT)removeAttr(QUOT;只读&QUOT)。  });

我用这个:

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

我尝试了上面的大部分建议,现在我用一条线就达到了最简单。将2个匿名html属性对象声明为“对象”并将其中的一个声明为“对象”类型。

@Html.TextBoxFor(m => m.Email, !isEdit ? new { id = "email_box" } : new { id = "email_box", @readonly = isEdit ? "readonly" : "false" } as object)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top