【发布时间】:2015-04-20 00:26:25
【问题描述】:
在我的 MVC5 Code-First 应用程序中,我的大部分视图中都显示了几个字段:[created_date]、[created_by]、[modified_date] 和 [modified_by]。对于用户,我想将这些也包含在我的Edit() 视图中,但与我的其他字段不同,我不希望它们可编辑(通常创建/由和修改/由数据不应该是可编辑的)。
这就是我目前在Edit() 视图中声明字段的方式:
<div class="form-group">
@*@Html.LabelFor(model => model.created_date, htmlAttributes: new { @class = "control-label col-md-2" })*@
<span class="control-label col-md-2">Created Date:</span>
<div class="col-md-10">
@Html.DisplayFor(model => model.created_date, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.created_date, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@*@Html.LabelFor(model => model.created_by, htmlAttributes: new { @class = "control-label col-md-2" })*@
<span class="control-label col-md-2">By:</span>
<div class="col-md-10">
@Html.DisplayFor(model => model.created_by, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.created_by, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@*@Html.LabelFor(model => model.modified_date, htmlAttributes: new { @class = "control-label col-md-2" })*@
<span class="control-label col-md-2">Modified Date:</span>
<div class="col-md-10">
@Html.DisplayFor(model => model.modified_date, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.modified_date, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@*@Html.LabelFor(model => model.modified_by, htmlAttributes: new { @class = "control-label col-md-2" })*@
<span class="control-label col-md-2">By:</span>
<div class="col-md-10">
@Html.DisplayFor(model => model.modified_by, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.modified_by, "", new { @class = "text-danger" })
</div>
</div>
谁能提供一种方法来制作这些字段read-only?
我在Details 视图上尝试DisplayFor(),但是当我去保存记录时,[created_date] 的EditorFor() 中的值从“2015-02-18" 到 "0001-01-01" 和 created_by 从我之前设置的系统用户名更改为 null 并带有验证消息“created_by 字段是必需的 。”我相信这与我对字段的模型注释有关,但我不明白为什么 DisplayFor() 没有像 EditorFor() 那样通过我的控制器传递值...?
模型注释:
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime created_date { get; set; }
[Required]
public string created_by { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime? modified_date { get; set; }
public string modified_by { get; set; }
【问题讨论】:
标签: asp.net-mvc razor asp.net-mvc-5 readonly editorformodel