I’m currently using Twitter’s Bootstrap toolkit on a new project and I had a question on the best way to use the modal dialog in ASP.NET MVC3.
Is the best practice to have a Partial that contains the modal’s markup and then use javascript to render that onto the page or is there a better approach?
Here goes my little tutorial which demonstrates Twitter’s Bootstrap (2.x) modal dialog that works with forms and partials in ASP.Net MVC 4.
To download similar project but targeting MVC 5.1 and Bootstrap 3.1.1 please visit this site.
Start with an empty MVC 4 Internet template.
Add reference to Bootstrap using NuGet
In the App_Start/BundleConfig.cs add the following lines:
In the Views/Shared/_Layout.cshtml
modify the @styles.Render line so it will look like:
and the @Scripts.Render line:
So far we have Bootstrap prepared to work with MVC 4 so let’s add a simple model class MyViewModel.cs to the /Models folder:
In the HomeController Add the following lines:
Create new Partial View in the Views/Home folder and name it _Create.cshtml:
In the Home/Index.cshtml remove the default content from the template and replace it with following:
If you run your application, a nice Bootstrap modal will appear after clicking the Create button on the Home page.
Try to uncomment the
SaveChanges() //throwline in HomeController.cs to prove that your controller handled errors will appear correctly in the dialog.I hope that my sample clarifies a bit whole process of incorporating Bootstrap and creating modals in the MVC application.