如何防止EditorTemplate逻辑覆盖视图逻辑?
本文关键字:视图 覆盖 何防止 EditorTemplate | 更新日期: 2023-09-27 18:17:29
使用MVC5,我添加了视图逻辑来禁用基于模型中的值的数据输入。在逻辑运行之后,它将被现有的EditorTemplate逻辑覆盖——该字段仍然是启用的。我怎样才能使我的禁用逻辑工作?这个视图逻辑首先运行:
<div>
@{
object attributes = new { @class = "form-control", @disabled = "disabled", @readonly = "readonly" };
if (Model.OnHold.Number == 0) {
attributes = new { @class = "form-control datePicker" };
}
@Html.EditorFor(model => model.OnHold.DateIssued, attributes);
}
</div>
然后冲突的EditorTemplate代码:
@model DateTime
@Html.TextBox(string.Empty, @Model.ToString("MM/dd/yyyy"), new { @class = "form-control datepicker" })
当您调用@Html.EditorFor(model => model.Property, attributesObj)
并且定义了自定义编辑器视图时,您可以看到该函数的智能感知表明htmlatattributes对象也包含在视图的ViewData
中。换句话说,如果您在编辑器视图中访问ViewData
属性,那么您应该可以访问从@Html.EditorFor(model => model.OnHold.DateIssued, attributes);
语句传递的属性。下面是一个简单的例子:
// Index.cshtml - assuming model.Message is of type string
@Html.EditorFor(model => model.Message, new { @class = "text-danger" })
// EditorTemplates/String.cshtml
@model string
@{
object textboxAttributes = new { @class = "text-success" };
// Override the default @class if ViewData property contains that key
if (ViewData.ContainsKey("class") && string.IsNotNullOrWhitespace(ViewData["class"].ToString())
{
textboxAttributes = new { @class = ViewData["class"] };
}
}
@Html.TextboxFor(model => model, textboxAttributes)
在你的例子中,你的EditorTemplate现在看起来像这样:
@model DateTime
@{
object dateAttributes = new { @class = "form-control datepicker" };
if (ViewData.ContainsKey("disabled") && !String.IsNullOrWhiteSpace(ViewData["class"].ToString()))
{
dateAttributes = new { @class = ViewData["class"], @readonly = "readonly", @disabled = "disabled" };
}
}
@Html.TextBox(string.Empty, @Model.ToString("MM/dd/yyyy"), dateAttributes)