Automatic Marking of Required Fields with EditorEntryFor

Using an EditorEntryFor helper makes the code DRYer and opens new possibilities, such as automatic indication of required fields. A small addition in one helper method will mark all required fields in entire MVC web application.

Required Fields MarkedIt’s more or less standard to indicate required fields in a form with a red * next to the label. Entering them one by one in the markup is tedious. Adding them to the description text is outright wrong and will look bad if the description is used in other places, such as validation messages.

They shouldn’t need to be handled at all, since the metadata already contains a property indicating if the field is required or not. If all form entries are created in the same way as I showed in the DRYing MVC Forms with an EditorEntryFor Helper post it’s easy to automatically add a required marker whenever a form field is required.

Instead of calling LabelFor directly, I’ve created an own helper method that checks the IsRequired flag on the metadata.

DRYing MVC Forms with an EditorEntryFor Helper

When creating forms in ASP.NET MVC I use a small helper to keep the code DRY (Don’t Repeat Yourself). The EditorEntryFor helper creates everything needed for a form field – the label, the input and the validation.

When creating line of business applications, a huge part of the coding is often to create forms. Each form can consist of a huge number of fields and each field requires some common formatting. It’s usually quite straightforward with a few divs surrounding a label and the input field. Running the default MVC scaffolding tooling, that’s exactly what’s generated:

<div class="editor-label">
    @Html.LabelFor(model => model.TopSpeed)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.TopSpeed)
    @Html.ValidationMessageFor(model => model.TopSpeed)
</div>

In my opinion that code has two severe problems:

  • It’s too verbose.
  • It’s repeating itself for each form field, making the class name and div structure a pain to modify.

In my projects I usually create a small helper, so the above lines of code can be replaced with one single statement:

@Html.EditorEntryFor(model => model.TopSpeed)
Software Development is a Job – Coding is a Passion

I'm Anders Abel, an independent systems architect and developer in Stockholm, Sweden.

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

Code for most posts is available on my GitHub account.

Popular Posts

Archives

Series

Powered by WordPress with the Passion for Coding theme.