5

I'm using the following code-snippet extensively in my model templates.

<div class="control-group">
    @Html.LabelFor(model => model.FirstName)
    <div class="controls">
        @Html.TextBoxFor(model => model.FirstName, new { @class = "span3" })
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>
</div>

Is it possible to encapsulate this generically in an editor template so I can use Html.EditorFor(...) without resorting to a custom extension?

batkuip
  • 1,480
  • 3
  • 15
  • 25

1 Answers1

9

Is it possible to encapsulate this generically in an editor template so I can use Html.EditorFor(...) without resorting to a custom extension?

Of course:

~/Views/Shared/EditorTemplates/Foo.cshtml:

<div class="control-group">
    @Html.Label("")
    <div class="controls">
        @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "span3" })
        @Html.ValidationMessage("")
    </div>
</div>

and then:

@Html.EditorFor(x => x.FirstName, "Foo")

or:

[UIHint("Foo")]
pubilc string FirstName { get; set; }

and then:

@Html.EditorFor(x => x.FirstName)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • You probably don't need the `"Foo"` on the last example. I had no idea you can use `("")` like that... Also, congratulations on *almost* reaching 300k. – Kobi Mar 27 '12 at 07:45
  • @Kobi, yes, I have just realized and fixed that. – Darin Dimitrov Mar 27 '12 at 07:46
  • Also if you use control-group syntax in many partial views you can abstract it away to a single method: http://stackoverflow.com/questions/4083147/how-to-abstract-common-snippets-of-markup-with-asp-net-mvc/14455144#14455144 – Lasse Skindstad Ebert Jan 22 '13 at 12:02
  • I would add: [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] also for MV6 I would use: http://blog.emikek.com/reinstating-imetadataaware-in-asp-net-5-vnext-mvc-6/ – Avlin Aug 11 '15 at 11:42