C# Corner

ASP.NET MVC 5.1 New Features, Part 2: Bootstrap Integration

ASP.NET MVC 5.1 has new HTML helpers that can be used to ease Bootstrap integration, as well as enum data type binding.

Last time I looked at new attribute routing options in ASP.NET MVC 5.1. In this second article in a series on ASP.NET MVC 5.1, I'll cover the new HTML helpers that are included that ease Bootstrap integration, as well as enum data type binding.

To get started, create a new ASP.NET MVC App from Visual Studio 2013. For the sample I'll be using Entity Framework Code First to set up a basic Create, Read, Update, Delete (CRUD) screen for Person table records. Next, create a PersonModel class under the Models directory in the solution. Then, add a PersonType enum to the PersonModel class with Client and Employee members. Next, add Id, FirstName, LastName, and Email properties to the class, as well as a Key attribute to the Id column. Listing 1 shows the completed PersonModel class.

Listing 1: PersonModel.cs
using System.ComponentModel.DataAnnotations;

namespace VSMMvc51Part2.Models
{
  public enum PersonType
  {
    Client,
    Employee
  }

  public class PersonModel
  {
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public PersonType PersonType { get; set; }
  }
}

Now that the PersonModel class is completed, let's add the Person controller class using Visual Studio scaffold. Right-click on the Controllers folder in the solution and click on Add Controller. Then, select the PersonModel class and available Data context class. Name the controller PersonController as shown in Figure 1.

[Click on image for larger view.] Figure 1. Adding Person Controller

Next, open up the Person controller Create action partial view under Views/Person/Create.cshtml file as shown in Listing 2.

Listing 2: Views/Person/Create.cshml Razor Partial View
@model VSMMvc51Part2.Models.PersonModel

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
  @Html.AntiForgeryToken()
    
  <div class="form-horizontal">
    <h4>PersonModel</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
      @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = 
        "control-label col-md-2" })
      <div class="col-md-10">
        @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = 
          "form-control" } })
        @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
      </div>
    </div>

    <div class="form-group">
      @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = 
        "control-label col-md-2" })
      <div class="col-md-10">
        @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = 
          "form-control" } })
        @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
      </div>
    </div>

    <div class="form-group">
      @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = 
        "control-label col-md-2" })
      <div class="col-md-10">
        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = 
          "form-control" } })
        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
      </div>
    </div>

    <div class="form-group">
      @Html.LabelFor(model => model.PersonType, htmlAttributes: new { @class = 
        "control-label col-md-2" })
      <div class="col-md-10">
        @Html.EnumDropDownListFor(model => model.PersonType, htmlAttributes: new { @class = 
          "form-control" })
        @Html.ValidationMessageFor(model => model.PersonType, "", new { @class = 
          "text-danger" })
      </div>
    </div>

    <div class="form-group">
      <div class="col-md-offset-2 col-md-10">
        <input type="submit" value="Create" class="btn btn-default" />
      </div>
    </div>
  </div>
}

<div>
  @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

You'll notice that the generated partial view code for the Create and Edit templates has been updated to use the new Html.EditorFor method that uses the htmlAttributes parameter. The generated code only uses the new Html.EditorFor for each property of the class, but you can make this more generic by just using Html.EdiforFor for the entire model, like this:

@Html.EditorForModel(new { htmlAttributes = new { @class = "form-control" } })

When you use EditorForModel and pass the htmlAttributes they'll be applied to all input and select controls in model. I still prefer the scaffold-generated code, though, because it uses the Bootstrap form-group and column-spacing classes to give a better overall layout.

Another new addition is ASP.NET MVC 5.1 is the Html.EnumDropDownListFor helper method that will generate a bound dropdown list for the given enum-based property. Figure 2 shows the completed Create form.

[Click on image for larger view.] Figure 2. Finished Create Form

As you can see, ASP.NET MVC 5.1 has some nice new HTML helper classes to make it easier to lay out your forms. In addition, Visual Studio 2013 ASP.NET MVC scaffolding has been improved to generate Bootstrap-friendly layouts and provides the flexibility to easily update your existing layouts through the updated Html.EditorFor and Html.EditorForModel templates. Also, the new Html.EnumDropDownListFor helper method makes it much easier to work with enum data type properties in your ASP.NET MVC views.

About the Author

Eric Vogel is a Senior Software Developer for Red Cedar Solutions Group in Okemos, Michigan. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at [email protected].

comments powered by Disqus

Featured

  • Creating Reactive Applications in .NET

    In modern applications, data is being retrieved in asynchronous, real-time streams, as traditional pull requests where the clients asks for data from the server are becoming a thing of the past.

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

  • .NET 9 Preview 3: 'I've Been Waiting 9 Years for This API!'

    Microsoft's third preview of .NET 9 sees a lot of minor tweaks and fixes with no earth-shaking new functionality, but little things can be important to individual developers.

  • Data Anomaly Detection Using a Neural Autoencoder with C#

    Dr. James McCaffrey of Microsoft Research tackles the process of examining a set of source data to find data items that are different in some way from the majority of the source items.

Subscribe on YouTube