Wednesday, April 1, 2015

How To Add a Bootstrap Alert to an MVC View

In this post we describe Step by step How To Add a Bootstrap Alert to an MVC View, in 5 minutes. We will display in an MVC View,  a message sent by a Controller , using the Bootstrap Alert component.
Essentially, all we need to do in order to add a Bootstrap Alert to an MVC View can be put this way:
1) Go to Bootstrap web site and copy the Alert HTML5 markup
2) Open the MVC View and paste the markup
3) Add an "if" condition to the View, to show the Alert

The Bootstrap Alert will show as follows:

How To Add a Bootstrap Alert to an MVC View

How To Add a Bootstrap Alert to an MVC View


First, let's go to the Bootstrap Official web site:
Add a Bootstrap Alert to an MVC View


Copy-paste the CDN urls containing the Bootstrap CSS3 and javascript, to your View(or _Layout):
Bootstrap Alert to an MVC View


We should use CDN (Content Delivery Network) because it is more efficient than including the javascript and CSS files in our application: CDN ensures quick delivery since it is spread on servers all around the world.
The Bootstrap scripts require JQuery to work, so browse to the JQuery official web site and get the latest version of the framework:
 MVC View


Again at the Boostrap web site, find the "Alert" Component, and Copy the HTML5 markup:

How To Add a Bootstrap Alert







Now, for this example of using the Alert component from the Bootstrap, we have a Controller which sets a TempData item as follows:
How To Add a Bootstrap Alert to an MVC


We will display that message in a View using the Bootstrap Alert.
Open your MVC View and select an appropriate place for placing the Alert. Paste the Alert markup there:
How To Add a Bootstrap to an MVC View



Write some C# code to show (or not) the Alert :
How To Add a Alert to an MVC View



In this case, if there is an TempData key containing a message, the Alert will be displayed:
How To Add a Bootstrap Alert to an MVC View

How To Add a Bootstrap Alert to an MVC View
The Bootstrap Alert can be closed or hidden by clicking the X icon :
How To Add a Bootstrap Alert to an MVC View




Happy programming.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן

No comments:

Post a Comment