26.06.2017 Views

Bootstrap for ASP.NET MVC

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Creating <strong>ASP</strong>.<strong>NET</strong> <strong>MVC</strong> <strong>Bootstrap</strong> Helpers<br />

Creating self-closing helpers<br />

Self-closing helpers are helpers that can contain HTML and Razor markup.<br />

The built-in @Html.BeginForm() helper is an example of this type of helper.<br />

In order to create this type of HTML helper, we'll need to create a helper class that<br />

implements the IDisposable interface. Using the IDisposable interface, we can<br />

write the element's closing tags when the object is disposed.<br />

The <strong>Bootstrap</strong> Panel component is a perfect candidate <strong>for</strong> such a helper. To create<br />

the helper, we'll have to complete the following steps:<br />

1. Create a new subfolder called Panels inside the Helpers folder in<br />

your project.<br />

2. Open the Enums.cs ile, and add a new item called PanelStyle:<br />

public enum PanelStyle<br />

{<br />

Default,<br />

Primary,<br />

Success,<br />

Info,<br />

Warning,<br />

Danger<br />

}<br />

3. Add a new class ile called Panel.cs to the Panels folder.<br />

4. Add a new private read-only ield to the class called _writer.<br />

5. Create a constructor <strong>for</strong> the Panel class that accepts three parameters.<br />

The irst is a reference to the HtmlHelper object, the second speciies the<br />

title of the panel, and the third indicates the style of the panel.<br />

6. Add the following code to the Panel class's constructor method:<br />

public Panel(HtmlHelper helper, string title, Enums.PanelStyle<br />

style = Enums.PanelStyle.Default)<br />

{<br />

_writer = helper.ViewContext.Writer;<br />

var panelDiv = new TagBuilder("div");<br />

panelDiv.AddCssClass("panel-" + style.ToString().ToLower());<br />

panelDiv.AddCssClass("panel");<br />

var panelHeadingDiv = new TagBuilder("div");<br />

panelHeadingDiv.AddCssClass("panel-heading");<br />

[ 104 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!