使用Html.TextBoxFor时,我可以将文本框设置为只读吗?

时间:2010-03-29 15:20:13

标签: .net html asp.net-mvc

我有一个带有Html.TextBoxFor表达式的以下标记,我希望内容只读,这可能吗?

<%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action)%>

15 个答案:

答案 0 :(得分:107)

<%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new { @readonly = true })%>

答案 1 :(得分:37)

根据评论中的@ 1c1cle建议更新现代版.NET:

<%= Html.TextBoxFor(model => Model.SomeFieldName, new {{"readonly", "true"}}) %>

要意识到这不是一种“安全”的方式,因为有人可以注入javascript来改变它。

需要注意的是,如果将readonly值设置为false,您实际上看不到行为的任何变化!因此,如果您需要根据变量驱动它,则不能简单地将该变量插入其中。相反,您需要使用条件逻辑来简单地不传递readonly属性。

这是一个未经测试的建议如何执行此操作(如果有问题,您可以随时执行if / else):

<%= Html.TextBoxFor(model => Model.SomeFieldName, shouldBeReadOnlyBoolean ? new {{"readonly", "true"}} : null) %>

答案 2 :(得分:35)

使用以下内容:

 @Html.TextBoxFor(m => m.Whatever, new {@readonly = "readonly"})

如果你想为它分配一个类,你可以通过添加相同的方式来实现它      @class =“”  属性。希望这会有所帮助:)

答案 3 :(得分:12)

将其设为只读

@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @readonly="true"})

禁用

@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @disabled="true"})

答案 4 :(得分:7)

<%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new {readonly=true})%>

答案 5 :(得分:7)

以下代码段对我有用。

@Html.TextBoxFor(m => m.Crown, new { id = "", @style = "padding-left:5px", @readonly = "true" }) 

答案 6 :(得分:4)

<%: Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new { @autocomplete = "off", @readonly=true})%>

这是您设置多个属性的方法

答案 7 :(得分:3)

这项工作对我来说......

@Html.TextBoxFor(model => model.RIF, new { value = @Model.RIF, @readonly = "readonly" })

答案 8 :(得分:2)

另一种可能性:

<%= Html.TextBoxFor(model => Model.SomeFieldName, new Dictionary<string, object>(){{"disabled", "true"}}) %>

答案 9 :(得分:1)

使用@Hunter的示例,在新的{..}部分中,添加readonly = true,我认为这样可行。

答案 10 :(得分:0)

事实上,Brain Mains的答案几乎是正确的:

@Html.TextBoxFor(model => model.RIF, new { value = @Model.RIF, @readonly = true })

答案 11 :(得分:0)

如果您必须应用自定义类,可以使用

  @Html.TextBoxFor(m => m.Birthday,   new Dictionary<string, object>() { {"readonly", "true"}, {"class", "commonField"} } )

在哪里

commonField 是CSS类

生日可能是您可能用来保持jQuery Datapicker日期的字符串字段:)

<script>
             $(function () {
                 $("#Birthday").datepicker({

                 });
             });
  </script>

这是一个真实的例子。

答案 12 :(得分:0)

通过将readonly属性设置为true或false在大多数浏览器中都不起作用,我已经完成了如下操作,当页面模式为“重新加载”时,我没有包含“readonly”属性。 / p>

@if(Model.Mode.Equals("edit")){
@Html.TextAreaFor(model => Model.Content.Data, new { id = "modEditor", @readonly = moduleEditModel.Content.ReadOnly, @style = "width:99%; height:360px;" })
}
@if (Model.Mode.Equals("reload")){
@Html.TextAreaFor(model => Model.Content.Data, new { id = "modEditor", @style = "width:99%; height:360px;" })}

答案 13 :(得分:0)

   @Html.TextBoxFor(model => model.IdUsuario, new { @Value = "" + User.Identity.GetUserId() + "", @disabled = "true" })

@disabled = "true"

工作得很好

答案 14 :(得分:0)

您还可以禁用TextBoxFor

@Html.TextBoxFor(x=>x.day, null, new { @class = "form-control success" ,@disabled="disabled" })