In the past, I’ve written extensively about Bootstrap 4 forms, as well as Bootstrap 4 modal popups. Today, let’s take a look at how to combine these two together with a Bootstrap modal form validation example. Since I work mostly in ASP.NET, I’m going to be using examples with that technology stack. However, you could certainly adapt this to whatever framework you might be using.
Wait!
Before you dive in to the next section, where you’ll be seeing a lot of code, I want to tell you about something that might make your day easier.
Sometimes it really helps to see code in context. Want to get the complete Visual Studio solution for every example in this post, and a whole lot more? You can get it, right now, in my book Bootstrap for .NET Devs. Check out the sample chapters instantly, for free.
[maxbutton id=”4” url=”https://sensibledev.com/recommends/bootstrap-for-dot-net-mvc-forms-1/” ]
Setting Up The Project
I’m using .NET Core in this example, but you can, of course, use the version of Visual Studio that you’re used to.
If you’re using a different technology stack, then set up a basic web app where you can accept a form submission.
Start by creating a new project. Name it BootstrapModal
and create a Web Application with no authentication.
Next, let’s make a model and database. We’ll use the boring old Employee example. I know, I know, it’s been done to death, but it works.
Creating a Model and Scaffolding the Database
Create a folder called Models in the root of the project. Inside the folder, create a file called Employee.cs.
public class Employee { public int ID { get; set; } public string Name { get; set; } public DateTime HireDate { get; set; } public bool IsManagement { get; set; }
}
Next, create a DbContext in the same folder called ApplicationContext.cs.
using Microsoft.EntityFrameworkCore;
public class ApplicationContext : DbContext
{
public ApplicationContext(DbContextOptions<ApplicationContext> options)
: base(options)
{ }
public DbSet<Employee> Employees { get; set; }
}
Now pop into appsettings.json. We’ll be providing a connection string to a test database. If you chose Individual Account authentication earlier, this part is probably already set up for you.
Add this ConnectionString section to the file:
{ “ConnectionStrings”: { “Default”: “Server=(localdb)\\mssqllocaldb;Database=TestDb;Trusted_Connection=True;ConnectRetryCount=0” }, “Logging”: { “LogLevel”: { “Default”: “Warning” } }, “AllowedHosts”: “*” }
In Startup.cs, you’ll now want to add the DbContext
with this line at the end of the ConfigureServices
method:
services.AddDbContext
Finally, we just need to use Entity Framework to scaffold our database. Enter following two commands into the package manager console:
Add-migration initial
Update-database
If all went well, you should now have a database with columns for your Employees.
Now, let’s make some Razor pages to get some basic CRUD functionality in place.
Create a folder called Employees. Right-click it and select:
Add -> Razor Page… -> Razor Pages Using Entity Framework (CRUD)
After you scaffold the Razor pages, try to build the project. You’ll get an error. This is because the current scaffolds don’t properly generate markup for a boolean property in Razor Pages.
To fix it, go to each view affected, and find this line:
@Html.DisplayNameFor(model => model.IsManagement))
Change the HTML helper to:
@Html.DisplayNameFor(model => model.Employee.IsManagement)
Now, when you debug, you ought to be fine.
Updating to Bootstrap 4
You’re going to want to upgrade from Bootstrap 3 to Bootstrap 4 at this point. The easiest way is to just head out to the official site and download the compiled Bootstrap 4 files.
Then, replace the Bootstrap CSS and Javascript files in wwwroot/lib/bootstrap/dist.
Update _Layout.cshtml:
Clear out the styles in wwwroot/css/site.css. You won’t need them, and they’ll get in the way more than help you. Just delete all the styles in the file and breathe a sigh of relief.
Creating a Bootstrap 4 Modal in ASP.NET
Head over to https://localhost:YOURPORT/Employees
. You’ll see an empty Index page.
Now, normally, when we click on “Create New,” we’ll be redirected to the Create page. Instead, we want this link to open up our modal.
Change the link to look like this:
And add the following markup below the table:
If you debug the project, you’ll see that clicking on “Create New” will now open the modal.
So let’s start to customize this a bit more. Change the `h5` with the title to reflect our entity:
Create Employee
Change the primary button to be a little bit more clear:
Next, we need to add our form. Go to Create.cshtml copy the form. (Don’t copy the entire Razor markup, obviously, just the form element.) Paste the form into the modal-body
div.
You should see Intellisense go crazy at this point, and underline all of your form field properties in red. That’s because the scaffolding named the IList of Employees the singular Employee
(as much sense as that makes).
To fix this, head to Index.cshtml.cs. Change the name of the list to Employees
. Then, add a property called Employee of the Employee
class type. Your class should look like this:
public IList
Finally, change the HTML helpers in your table to match the Employees
list you just renamed. In other words, as an example, the first th
should look like this:
Your form should look something like this.
Also, we need the validation scripts from the Create page in order to validate our fields before the form submission. Place this at the bottom of Index.cshtml:
@section Scripts { @{await Html.RenderPartialAsync(“_ValidationScriptsPartial”);} }
Okay, now we’re getting somewhere!
Fixing the Form
Of course, we still have a few issues to iron out. The styles are still in Bootstrap 3 styles instead of 4, so we’ll need to fix that. There are now two submit buttons, so we’ll need to get rid of one. The more important issue is that the form will try to POST to our Index method… which, of course, doesn’t exist.
First, let’s update a few things to be in line with Bootstrap 4.
Labels no longer need the `control-label` class, so you can get rid of the class="control-label"
attributes.
The checkbox layout is completely different from what asp-for
generates, so take out the form group with the checkbox and replace it with this:
We now should be good with the styling.
Next, we need to have the form POST to our Create method, at /Employees/Create
.
If you were following the online .NET Core documentation at this point, you might have tried something like this:
The `novalidate` attribute will make it so that the browser validation styles won't override our Bootstrap styles. Next, add the fields into the form: