MVC3 EditorFor readOnly

who*_*ee1 65 readonly editorfor asp.net-mvc-3

我想在编辑页面中使用EditorFor进行readOnly.

我尝试将readonly和disabled设置为:

<div class="editor-field">
        @Html.EditorFor(model => model.userName, new { disabled = "disabled", @readonly = "readonly" })
    </div>
Run Code Online (Sandbox Code Playgroud)

但是,它不起作用.如何禁用编辑此字段?

谢谢.

dan*_*wig 87

EditorFor html帮助程序没有带有HTML属性的重载.在这种情况下,您需要使用更具体的内容,如TextBoxFor:

<div class="editor-field">
    @Html.TextBoxFor(model => model.userName, new 
        { disabled = "disabled", @readonly = "readonly" })
</div>
Run Code Online (Sandbox Code Playgroud)

您仍然可以使用EditorFor,但是您需要在自定义的EditorTemplate中使用TextBoxFor:

public class MyModel
{
    [UIHint("userName")]
    public string userName { ;get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后,在Views/Shared/EditorTemplates文件夹中,创建一个文件userName.cshtml.在那个文件中,把这个:

@model string
@Html.TextBoxFor(m => m, new { disabled = "disabled", @readonly = "readonly" })
Run Code Online (Sandbox Code Playgroud)

  • 在较新版本的MVC中(我相信4+?),`additionalViewData`对象可以有`htmlAttributes`属性,`EditorFor`等用于html属性.所以它将成为:`@ Html.EditorFor(model => model.userName,new {htmlAttributes = new {disabled ="disabled",@ readonly ="readonly"}})`. (3认同)

GSo*_*ing 29

MVC4以上版本支持此代码

@Html.EditorFor(model => model.userName, new { htmlAttributes = new { @class = "form-control", disabled = "disabled", @readonly = "readonly" } })
Run Code Online (Sandbox Code Playgroud)

  • 现在应该是公认的答案 (2认同)

Sei*_*chi 12

对于那些想知道你为什么要使用EditoFor的人,如果你不想让它可以编辑,我就有一个例子.

我的模型中有这个.

    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0: dd/MM/yyyy}")]
    public DateTime issueDate { get; set; }
Run Code Online (Sandbox Code Playgroud)

当你想要显示那种格式时,它唯一的工作方式是使用EditorFor,但是我有一个jquery datepicker用于那个"输入"所以它必须是只读的,以避免用户写错错误的日期.

为了让它按照我想要的方式工作,我把它放在视图中......

     @Html.EditorFor(m => m.issueDate, new{ @class="inp", @style="width:200px", @MaxLength = "200"})
Run Code Online (Sandbox Code Playgroud)

这是我准备好的功能......

     $('#issueDate').prop('readOnly', true);
Run Code Online (Sandbox Code Playgroud)

我希望这对那里的人有所帮助.对不起我的英语不好


小智 6

你可以这样做:

@Html.EditorFor(m => m.userName, new { htmlAttributes = new { disabled = true } })
Run Code Online (Sandbox Code Playgroud)


sto*_*roz 5

我知道问题是 MVC 3,但那是 2012 年,所以以防万一:

从 MVC 5.1 开始,您现在可以传递 HTML 属性,EditorFor如下所示:

@Html.EditorFor(x => x.Name, new { htmlAttributes = new { @readonly = "", disabled = "" } })
Run Code Online (Sandbox Code Playgroud)