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

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube