Bootstrap 3 With MVC 5 And Entity Framework 6 Database First

Sometime back, I’ve created a sample MVC 5 application with Bootstrap 3. In that article, I’ve explained how to change the default bootstrap layout. Recently, I got several requests to include MVC controls with bootstrap styling in the example. So, here is another step-by-step article on using Bootstrap 3 with MVC 5 and Entity Framework 6 with Database First workflow, to demonstrate how to use the ASP.NET MVC controls with bootstrap look and feel.

Bootstrap 3 With MVC 5 And Entity Framework 6

In this step-by-step example, I’ll be using few of the tables and data from WideWorldImporters sample database for SQL Server 2016 using the database first workflow in Entity Framework. If you don’t have SQL Server 2016 or WideWorldImporters sample database, then follow the articles Installing SQL Server 2016 and Installing SQL Server Sample Database to install them.

Overview Of This Article

  • Creating a sample MVC 5 project in Visual Studio 2015 using Entity Framework 6 database first workflow.
  • Upgrading default Bootstrap and other NuGet packages to the latest stable version.
  • Changing the default Bootstrap layout to another.
  • Connect a sample database with Entity Framework database first workflow.
  • Customizing and styling some of the ASP.NET MVC controls using Bootstrap classes.

Tools & Technologies Used

  • Visual Studio Community 2015.
  • .Net Framework 4.6.1
  • ASP.NET MVC 5.2.3
  • Entity Framework 6.1.3 (Database First Workflow)
  • Bootstrap 3.3.7
  • jQuery 3.1.0
  • jQuery.Validation 1.15.1
  • SQL Server 2016 Developer Edition
  • WideWorldImporters OLTP sample database for SQL Server 2016 Developer Edition
  • Microsoft Edge and Chrome Browser

Sample Source Code:

The sample source code, project and solution created with this step-by-step instruction is available in my GitHub repository. Download or fork the sample code from here.

Steps For Using Bootstrap 3 With MVC 5 And Entity Framework 6

I. Creating MVC 5 Project

  1. Launch Visual Studio 2015 (I’ve used Visual Studio Community 2015).
  2. Go to File menu and select New Project…
  3. Create a new C#, ASP.NET Web Application (.NET Framework) project With .NET Framework 4.6.1. Bootstrap3 with ASP.NET MVC5 and EF6 01
  4. In the next screen, select MVC as the template. Then press the Change Authentication button and change the authentication to No Authentication. Then press OK.
    Bootstrap3 with ASP.NET MVC5 and EF6 02
  5. Press OK In in template selection screen. The MVC 5 project with Bootstrap 3 is now created.

II. Update The Default NuGet Packages

Because we have used the MVC template for creating the project, the project is created with some basic NuGet packages like Bootstrap, jQuery, jQuery.Validation, etc… These packages are in older version. It will be a good practice to upgrade them to the current stable versions before starting any coding in the project. Follow the below steps to update the NuGet packages to the current stable versions.

  1. Right click the solution in solution explorer and select Manage NuGet Packages for Solution...
    Bootstrap3 with ASP.NET MVC5 and EF6 03
  2. In the Manage Packages for Solution screen open the Updates section. You will see the list of packages which has update to the latest stable version.
    Bootstrap3 with ASP.NET MVC5 and EF6 04
  3. Select all the packages and press Update button.
  4. The package manager checks for dependencies and pop-up a window which will have the packages latest versions and their dependencies. Press OK to continue the update process.
    Bootstrap3 with ASP.NET MVC5 and EF6 05
  5. Accept the license agreements if the License Acceptance screen appears.
    Bootstrap3 with ASP.NET MVC5 and EF6 06
  6. The packages are updated to the corresponding latest stable versions. The older version files are removed from the project. You can see the update status in the output panel.
    Bootstrap3 with ASP.NET MVC5 and EF6 07
  7. Some package updates may need the Visual Studio to be restarted. So, it is good to restart the visual studio before proceeding further.

III. Install Entity Framework

  1. To install Entity Framework, go back to the Manage NuGet Packages for Solution screen and select the Browse panel.
  2. The Browse panel lists down the top downloaded packages. You can find the EntityFramework package among the top few in the list. If not, you can search for “EntityFramework” using the search box. In the right panel of the screen you can see the version number of the package. Select the EntityFramework package and choose the projects you want the package to install. Then press Install.
    Bootstrap3 with ASP.NET MVC5 and EF6 08
  3. Press OK in the Preview window and Accept the License Agreement.
  4. The EntityFramework (version 6.1.3) package is installed and you can now see the Entity Framework assemblies under the Reference folder in the Solution Explorer.
    Bootstrap3 with ASP.NET MVC5 and EF6 11

IV. Changing Bootstrap Layout & Style Of Project

The default bootstrap template used in Visual Studio 2015 is Jumbotron. When you create a project with a template, the layout and the index page will have the Jumbotron layout code, modified to accommodate the MVC structure. Jumpotron’s source code is available here in bootstrap website. For this example, to get used to the bootstrap layout, we’ll change this layout to another one. Let’s use the Justified-Nav template from bootstrap website. You can get the HTML code from bootstrap website. Justified-Nav is also a fluid layout template which will re-align itself for the screen size.

When changing the default bootstrap layout in MVC, you have to understand that the bootstrap layout is segregated into 2 parts. In most cases, head, navigation and the footer section goes to the MVC layout file (_Layout.cshtml). The content part (ie. the bootstrap grid system with row and col) alone goes to the index and other views.

Follow the below steps to change the default Jumbotron layout to Justified-Nav.

  1. Get the source code of Justified-Nav template from https://getbootstrap.com/docs/3.3/examples/justified-nav/.
  2. The Justified-Nav template needs extra style sheet (justified-nav.css). You can get it from the bootstrap website from here. (or you can download it from my GitHub repository)
  3. Place the style sheet justified-nav.css to the Content folder and attach it to the project.
    Bootstrap3 with ASP.NET MVC5 and EF6 12
    Bootstrap3 with ASP.NET MVC5 and EF6 13
  4. Open the BundleConfig.cs under the project’s App_Start Folder.
  5. Add the justified-nav.css to the “~/Content/css” style bundle below the bootstrap.css.
    Bootstrap3 with ASP.NET MVC5 and EF6 14
  6. Now, open the layout file _Layout.cshtml in the Shared folder under Views Folder.
  7. In the layout file, you have to change only the top navigation part of the bootstrap. For that, remove the section within the <body> tag.
    Bootstrap3 with ASP.NET MVC5 and EF6 15
  8. Instead of the removed section, paste the below code.

    <div class=”container”>
    <div class=”masthead”>
    <h3 class=”text-muted”>Wide World Importers</h3>
    <nav>
    <ul class=”nav nav-justified”>
    <li class=”active”><a href=”#”>Home</a></li>
    <li><a href=”#”>Projects</a></li>
    <li><a href=”#”>Services</a></li>
    <li><a href=”#”>Downloads</a></li>
    <li><a href=”#”>About</a></li>
    <li><a href=”#”>Contact</a></li>
    </ul>
    </nav>
    </div>

    @RenderBody()

    <!– Site footer –>
    <footer class=”footer”>
    <p>&copy; 2016 www.MyTecBits.com</p>
    </footer>
    </div> <!– /container –>

    Bootstrap3 with ASP.NET MVC5 and EF6 16

  9. Open the Index.cshtml file in the Home folder under Views. For this example, I’m not going to change the content of this file now. This existing content will work well the current Bootstrap Justified-Nav template. If you want you can change it using the bootstrap grid system using one or many rows and columns. Read more about bootstrap grid system here.
    Bootstrap3 with ASP.NET MVC5 and EF6 17
  10. Now, Build the solution and execute. You will get the new bootstrap 3 Justified-Nav layout in ASP.NET MVC 5. This is a fluid layout which re-align itself based on the size of the display.
    Bootstrap3 with ASP.NET MVC5 and EF6 18
    Bootstrap3 with ASP.NET MVC5 and EF6 19

V. Creating Models

Now we will use the Entity Framework to create the models from the SQL Server database tables. I’ll be using SQL Server 2016 and it’s sample database WideWorldImporters for this example. You can use any other database if you are comfortable with following this instruction with another table and data. Or, you can install SQL Server 2016 and WideWorldImporters sample database by following the articles Installing SQL Server 2016 and Installing SQL Server Sample Database. Once you have the database and tables in place, proceed to the below steps.

Steps For Creating Entity Data Model Using Database First Workflow

  1. In the solution explorer, select the Models folder and right-click. In the right-click menu select Add and then New Item...
    Bootstrap3 with ASP.NET MVC5 and EF6 20
  2. In the New Item screen, select Data under Visual C#. Then select ADO.NET Entity Data Model. Change the name to WideWorldImportersModel (I’ve used the model name as WideWorldImportersModel as I’m using the WideWorldImporters database. You can use a different model name, in case if you are using a different database). After entering the name of the model, press Add.
    Bootstrap3 with ASP.NET MVC5 and EF6 21
  3. The Entity Data Model Wizard will pop up. In the wizard, select the option EF Designer from database (Because we are following database first entity framework workflow). Press Next to continue.
    Bootstrap3 with ASP.NET MVC5 and EF6 22
  4. In the Choose Your Data Connection screen, press New Connection… button to create a connection to the database.
    Bootstrap3 with ASP.NET MVC5 and EF6 23
  5. In the Connection Properties screen, use the drop-down box for the server name to select the server which has your sample database (In my case, it’s my local pc MACWINDOWS). Choose the proper authentication to log on to your SQL Server (In my case, it’s Windows Authentication). Then, select the database, as we are using the Microsoft’s sample database WidwWorldImporters, select it from the drop-down box under Select or enter a database name. Before pressing the OK button, test the connection by pressing the Test Connection button. If the test connection succeeds, then press the OK button. (If you get any error during test connection, check the database connection details you have entered).
    Bootstrap3 with ASP.NET MVC5 and EF6 24
  6. Now, the new connection is created and displayed in the Choose Your Data Connection screen. Press Next button to continue.
    Bootstrap3 with ASP.NET MVC5 and EF6 25
  7. In the Choose Your Database Objects and Settings screen, expand the schema Application under Tables. Select the tables which are NOT ending with _Archive. Finally press Finish button.
    Bootstrap3 with ASP.NET MVC5 and EF6 26
  8. The system will take few seconds to a minute or so to generate the model. In-between if you get any security warning message, press OK to continue.
    Bootstrap3 with ASP.NET MVC5 and EF6 27
  9. Once the Entity Framework Model is generated, Visual Studio will display a table relationship diagram with the tables you have selected to generate the model.
    Bootstrap3 with ASP.NET MVC5 and EF6 28
  10. Close the model diagram and see the Models folder in Solution Explorer. You can see several new files generated by the Entity Data Model Wizard.
    Bootstrap3 with ASP.NET MVC5 and EF6 29
  11. Now build the project or solution. This is important. If you go ahead further without building the project, you will get errors while using this model.

VI. Creating Views And Controllers

In this section we will create the views and controllers for the model using scaffolding method.

  1. In the Solution Explorer, Select the Controllers folder and right-click. In the right-click menu, select Add and then New Scaffolded Item…
    Bootstrap3 with ASP.NET MVC5 and EF6 30
  2. In the Add Scaffold screen, select MVC in the left panel and MVC 5 Controller with views, using Entity Framework from the center panel. Press Add button.
    Bootstrap3 with ASP.NET MVC5 and EF6 31
  3. In the Add Controller screen, select the model class Person from the drop-down list. Then select the context class WideWorldImportersEntities. Press Add to generate the controller and the corresponding views.
    Bootstrap3 with ASP.NET MVC5 and EF6 32
  4. In the Solution Explorer, you can see the controller PeopleController.cs and the views Create, Delete, Details, Edit and Index under the People folder in Views.
    Bootstrap3 with ASP.NET MVC5 and EF6 33

VII. Checking The Newly Generated Views

Let’s check the new People views generated by scaffolding. To navigate to the views, we’ll change a menu item in the layout file.

  1. Open the _Layout.cshtml file under Views >> Shared folder.
  2. In the navigation menu, change the code <li><a href=”#”>Projects</a></li> to:

    <li>@Html.ActionLink(“People”, “Index”, “People”)</li>

    Bootstrap3 with ASP.NET MVC5 and EF6 34

  3. Now, build the project and view in browser. The home page will be like this:
    Bootstrap3 with ASP.NET MVC5 and EF6 35
  4. Press the People menu to launch the index view of People. You will notice all the records from the people table will be listed making you to scroll to the right to see the Edit, Details and Delete Links. We will customize this views and give a better look and feel using bootstrap styles.
    Bootstrap3 with ASP.NET MVC5 and EF6 36

VIII. Customizing Views Using Bootstrap Classes

The MVC project is now ready to apply the bootstrap classes and customize further. In this section, I’ll show you how to change the style of some of the ASP.NET MVC controls and some of the basic html controls using bootstrap.

Remove Unwanted Data Fields From Index View

  1. Open the Index.cshtml view file under Views >> People.
  2. In this file, leave the fields FullName, PreferredName, IsPermittedToLogon, PhoneNumber, EmailAddress and the Edit, Details, Delete action links and remove the other fields from the table’s head and body. The resultant code in the file will be like this.

    @model IEnumerable<MyTecBits_MVC5_Bootstrap3_EF6_DatabaseFirst.Models.Person>

    @{
    ViewBag.Title = “Index”;
    }

    <h2>Index</h2>
    <p>@Html.ActionLink(“Create New”, “Create”)</p>

    <table class=”table”>
    <tr>
    <th>
    @Html.DisplayNameFor(model => model.FullName)
    </th>
    <th>
    @Html.DisplayNameFor(model => model.PreferredName)
    </th>
    <th>
    @Html.DisplayNameFor(model => model.IsPermittedToLogon)
    </th>
    <th>
    @Html.DisplayNameFor(model => model.PhoneNumber)
    </th>
    <th>
    @Html.DisplayNameFor(model => model.EmailAddress)
    </th>
    <th>Action</th>
    </tr>

    @foreach (var item in Model)
    {
    <tr>
    <td>
    @Html.DisplayFor(modelItem => item.FullName)
    </td>
    <td>
    @Html.DisplayFor(modelItem => item.PreferredName)
    </td>
    <td>
    @Html.DisplayFor(modelItem => item.IsPermittedToLogon)
    </td>
    <td>
    @Html.DisplayFor(modelItem => item.PhoneNumber)
    </td>
    <td>
    @Html.DisplayFor(modelItem => item.EmailAddress)
    </td>
    <td>
    @Html.ActionLink(“Edit”, “Edit”, new { id = item.PersonID }) |
    @Html.ActionLink(“Details”, “Details”, new { id = item.PersonID }) |
    @Html.ActionLink(“Delete”, “Delete”, new { id = item.PersonID })
    </td>
    </tr>
    }
    </table>

    Bootstrap3 with ASP.NET MVC5 and EF6 37

  3. On loading in the browser, the people index view looks like this.
    Bootstrap3 with ASP.NET MVC5 and EF6 38

Styling Html.ActionLink As Bootstrap Buttons

Now, you’ll see how to style the action link html helper to display it like a button. The bootstrap class for button is btn followed by the options btn-default, btn-primary, btn-syccess, btn-info, btn-warning, btn-danger and btn-link. To apply bootstrap button class in html action link helper class, you have to use the htmlAttributes object parameter.

  1. In the Index.cshtml, In Create New action link, add null for RouteValues parameter new { @class = “btn btn-default” } for htmlAttribute.
    Bootstrap3 with ASP.NET MVC5 and EF6 39
  2. Do the same for the other action links Edit, Details and Delete. For delete action you can set the bootstrap button option as btn-warning, so as to highlight the button to the users to be careful on using the button.
    Bootstrap3 with ASP.NET MVC5 and EF6 40
  3. Now, load the project in browser and check the people index view. See the beautiful Create New, Edit, Details and Delete buttons.
    Bootstrap3 with ASP.NET MVC5 and EF6 41

Styling Html.DisplayFor Text With Bootstrap CSS Class

Html.DisplayFor does not comes with the HtmlAttribute parameter to add the CSS class. So, you have to do some workaround to style the data displayed by Html.DisplayFor helper. There are two ways:

  • Wrap the DisplayFor with a div, paragraph or span tag and apply the CSS class in the wrapper tag, like <div class=”text-uppercase”>@Html.DisplayFor(modelItem => item.FullName)</div> to display the text in upper case.
    Bootstrap3 with ASP.NET MVC5 and EF6 41b
  • Another option is to create custom display template. Follow these steps to create a custom template with bootstrap CSS classes and apply the template to Html.DisplayFor.
    1. Create a folder DisplayTemplates under Views\Shared\.
    2. Create an empty view called class.cshtml without layout under DisplayTemplates folder.
      Bootstrap3 with ASP.NET MVC5 and EF6 42
    3. Remove all the code in the class.cshtml and add the below code.

      <span @(ViewData[“class”] != null ? “class=” + ViewData[“class”] + “” : string.Empty)>
      @ViewData.TemplateInfo.FormattedModelValue
      </span>

      Bootstrap3 with ASP.NET MVC5 and EF6 43

    4. Now, go back to the people index view and add a ViewData with name as class. Assign a bootstrap class say text-uppercase as value to ViewData[“class”]. Then add “class” to the Html.DisplayFor as second parameter.
      Bootstrap3 with ASP.NET MVC5 and EF6 44

Now load the project in browser and check the FullName and the PreferredName fields. For PreferredName field, I have used the wrapper method to apply the bootstrap class. For FullName field, I have used DisplayTemplate method. Both options displays similar result. It’s up to you to decide which method is good for your application. In this example I’ve used Bootstrap’s text-uppercase styling. You can use any type of bootstrap class using these methods.

Bootstrap3 with ASP.NET MVC5 and EF6 45

Styling Table With Bootstrap CSS Class

Styling of html table is very easy using bootstrap. I’ll apply few bootstrap classes to style the table in People’s Index view. As the table is created just by plain html, styling it is straight forward. To apply table classes, first add the class table to the <table> tag, then append the options like table-striped, table-bordered, table-hover, etc.

For example, I’ll add the table-striped option to display alternate row in different background color which appears like stripe.

Bootstrap3 with ASP.NET MVC5 and EF6 46

Bootstrap3 with ASP.NET MVC5 and EF6 47

I’ll also add a bluish background color for the header row. To do this I’ve to add the info class to the table’s header <tr>.

Bootstrap3 with ASP.NET MVC5 and EF6 48

Bootstrap3 with ASP.NET MVC5 and EF6 49

Making Bootstrap Menu Active Or In-Active

If you noticed the bootstrap menu, the Home menu is always active even when we are in People’s views.In bootstrap you can make a menu item active by adding the active class to the list item, i.e. <li class=”active”><a href=”#”>Services</a></li>.

To make the menu item active dynamically based on the current MVC controller loaded, you have to add a line of razor code for each of the menu items. Just add class=”@(ViewContext.RouteData.Values[“Controller”].ToString() == “People” ? “active” : “”)” to the list item <li> tag of the People Menu. Do this to the other menu items by changing the controller name in the razor code.

Bootstrap3 with ASP.NET MVC5 and EF6 50

Now, load the project in browser and check the menu. You can see the menu items are active or inactive based on the loaded controller.

Bootstrap3 with ASP.NET MVC5 and EF6 51

Styling Html.ValidationSummary and Html.ValidationMessageFor With Bootstrap Classes

The html helper controlls Html.ValidationSummary and Html.ValidationMessageFor has htmlAttributes object parameter. You can add the bootstrap classes in the htmlAttributes parameter to style the validation summary text. To try that, Open the Edit.cshtml view file under Views/People/. You will see the two controls I’ve just mentioned are there and they are already using the htmlAttributes to apply the bootstrap class text-danger.

Bootstrap3 with ASP.NET MVC5 and EF6 52

You can add another bootstrap class (let’s say mark to highlight the text) to these htmlAttributes.

Bootstrap3 with ASP.NET MVC5 and EF6 53

Load the create view in browser by pressing the Create New button in People’s Index view. In the persionID field enter some Non-Numeric characters and tab out. You will see the error message below the text box highlighted in yellow

Bootstrap3 with ASP.NET MVC5 and EF6 54

Styling Html.LabelFor With Bootstrap Classes

Html.LabelFor also has a parameter for htmlAttributes. You can use it to add the bootstrap class to the label text. This is similar to how you’ve added bootstrap class to Html.ValidationSummary and Html.ValidationMessageFor.

For example, If you want to add primary background color for the PersonID label, Then you’ve to add the bootstrap helper class bg-primary to the htmlAttributes parameter like @Html.LabelFor(model => model.PersonID, htmlAttributes: new { @class = “bg-primary” }).

Bootstrap3 with ASP.NET MVC5 and EF6 55

Bootstrap3 with ASP.NET MVC5 and EF6 56

Styling Html.EditorFor With Bootstrap Classes

Adding bootstrap classes to Html.EditorFor is little different from what we have seen so far. Html.EditorFor has a provision to induce the htmlAttributes through the additionalViewData parameter. You can add the htmlAttribute like new { htmlAttributes = new { @class = “form-control” } } in additionalViewData parameter.

For example, if you want to make a form control text box larger than the default size, then you have to add the bootstrap class input-lg like this: new { htmlAttributes = new { @class = “form-control input-lg” } } in additionalViewData parameter.

Bootstrap3 with ASP.NET MVC5 and EF6 57

Bootstrap3 with ASP.NET MVC5 and EF6 58

 

With this, I’m completing this article. Please, Note that the scope of the article is to demonstrate the usage of bootstrap styling in ASP.NET MVC 5 with EF 6 and it’s helper classes and controls. So, with the current code, you may get errors while saving the Edit and Create New forms. Later, when time permits, I’ll try to fix these issues.

You can download the source code from my GitGub Repositary @ MyTecBits-MVC5-Bootstrap3-EF6-DatabaseFirst.

Related Articles

Reference

  • Bootstrap @ https://getbootstrap.com/.


9 thoughts on “Bootstrap 3 With MVC 5 And Entity Framework 6 Database First”

  1. I considered my skills a UI design very poor and using Bootstrap was beyond me. This article has given me the much needed start to explore this area. Thank you very much!!

    Reply

Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.