Need some clarification about different types of Razor HTML-input syntax

Viewed 28

I'm working on a project in .NET Core 3.1, and have came accross diffrent types of syntax for HTML-inputs types. When looking at the compiled html source code, they look identical.

What is the difference? which one is prefered?

            //Alternative 1
            <div class="col-md-6 mb-3">
                @Html.LabelFor(x => x._user.UserProfileId, "Användarprofil*", htmlAttributes: new { @class = "form-label mb-0 fw-bold" })
                @Html.DropDownListFor(x => x._user.UserProfileId, new SelectList(profiles, "Id", "Name"), "Välj", htmlAttributes: new { @class = "form-select  form-select-lg", id = "Id", required = true})
                @Html.ValidationMessageFor(x => x._user.UserProfileId, "Error message", new { @class = "invalid-feedback" })
            </div>
            
            //Alternative 2
            <div class="col-md-6 mb-3">
                <label asp-for="_user.UserProfileId" class="form-label mb-0 fw-bold">Användarprofil*</label>
                <select asp-items="@(new SelectList(@profiles,"Id", "Name"))" asp-for="_user.UserProfileId" class="form-select  form-select-lg" aria-label="Användarprofil" required>
                    <option value="">Välj</option>
                </select>
                <div class="invalid-feedback">
                    Error message
                </div>
            </div>
1 Answers

The HTML helpers (LabelFor, DropDownFor etc) were introduced in the first version of ASP.NET back in 2008 or so. The second approach uses Tag helpers which were introduced as a new feature in ASP.NET Core. HTML helpers were retained in ASP.NET Core mainly to enable easier migration of views in existing full framework applications to .NET Core.

Tag Helpers are recommended for all new development. They have been implemented in a "designer friendly" way so that team members who are UI specialists can work with them more easily than with C# methods that have multiple overloads (which is essentially what the HTML helpers are).

Related