0

I'm trying to auto focus on a different area of a form depending on a field in the model. The following always renders the autofocus.

@Html.EditorFor(model => model.ManufacturerProduct.Specifications, new { htmlAttributes = new { @class = "form-control", autofocus = (Model.FocusOn == "Specifications" ? "" : null) } })

What I managed to do to get it to work was this, but it feels clunky.

@{
    dynamic expando = new ExpandoObject();
    expando.@class = "form-control";
    if (Model.FocusOn == "Specifications") expando.autofocus = "autofocus";
}

@Html.EditorFor(model => model.ManufacturerProduct.Specifications, new { htmlAttributes = expando })

Is there a better way?

feihtthief
  • 6,403
  • 6
  • 30
  • 29
  • Its the presence of the `autofocus` attribute which determines if its focused (`autofocus="true"` and `autofocus="false"` and `autofocus="anything"` all mean the same thing) –  Aug 17 '17 at 13:38
  • I understand WHY it's doing it, which is how I came up with the Expando solution. I'm just wondering if there is a better, more elegant solution that could work in a one-line ternary-type style. – feihtthief Aug 17 '17 at 13:40
  • You don't really need `Expando` - you could just use `object` - refer [this answer](https://stackoverflow.com/questions/34889537/conditional-html-attribute-with-html-helper/34889685#34889685) for an example. Of just a simple `@if (if (Model.FocusOn == "Specifications") { @Html.EditorFor(...) } else { @Html.EditorFor(...) }` –  Aug 17 '17 at 13:44

0 Answers0