如何防止EditorTemplate逻辑覆盖View逻辑?

时间:2016-11-10 13:38:21

标签: c# asp.net-mvc razor asp.net-mvc-5 mvc-editor-templates

使用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" })

1 个答案:

答案 0 :(得分:1)

当您调用@Html.EditorFor(model => model.Property, attributesObj)并且定义了自定义编辑器视图时,您可以看到该函数的intellisense表示htmlAttributes对象也包含在视图的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)