DeveloperDan DeveloperDan - 1 year ago 70
C# Question

How can I prevent EditorTemplate logic from overriding View logic?

Using MVC5 I've added view logic to disable data entry based on a value in the model. After the logic runs it is overridden by existing EditorTemplate logic - the field remains enabled. How can I make my disable logic work? This view logic runs first:

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);

Then the conflicting EditorTemplate code:

@model DateTime

@Html.TextBox(string.Empty, @Model.ToString("MM/dd/yyyy"), new { @class = "form-control datepicker" })

Answer Source

When you call @Html.EditorFor(model => model.Property, attrbiutesObj) and you have a custom editor view defined, you can see that the intellisense for the function says that the htmlAttributes object is also included in the ViewData of the view. In other words, if you access the ViewData property within your editor view, you should have access to the properties you're passing from your @Html.EditorFor(model => model.OnHold.DateIssued, attributes); statement. Here's a simple example:

// 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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download