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 />

<strong>ASP</strong>.<strong>NET</strong> <strong>MVC</strong> provides a range of standard, out-of-the-box HTML helpers.<br />

For example, to produce the following HTML <strong>for</strong> a textbox with an ID and name<br />

attribute of CustomerName, use the following code:<br />

<br />

You should use the TextBox helper as illustrated in the following code:<br />

@Html.TextBox("CustomerName")<br />

Majority of the built-in HTML helpers offer several overloaded versions. For<br />

instance, to create a textbox and explicitly set its name and value attributes, you<br />

should use the following overloaded TextBox helper method:<br />

@Html.TextBox("CustomerName"","Northwind Traders")<br />

Most built-in helpers also offer the option to specify HTML attributes <strong>for</strong> the element<br />

that is generated by passing in an anonymous type. In the following example, we'll<br />

create a textbox and set its style property using one of the overload methods:<br />

@Html.TextBox("CustomerName","Northwind Traders", new {<br />

style="background-color:Blue;" })<br />

You can read more about the standard HTML helpers available in<br />

<strong>ASP</strong>.<strong>NET</strong> <strong>MVC</strong> at http://bit.ly/<strong>MVC</strong>FormHelpers.<br />

Creating a custom helper<br />

As <strong>Bootstrap</strong> offers a variety of different components, it lends itself perfectly towards<br />

the use of helpers. The simplest <strong>for</strong>m of helper in <strong>ASP</strong>.<strong>NET</strong> <strong>MVC</strong> is the one that<br />

you can create using the @helper syntax. A custom helper can include any HTML<br />

or even Razor markup. To create a simple helper method to generate a <strong>Bootstrap</strong><br />

button, complete the following steps:<br />

1. Create a new folder called App_Code inside the root folder of your website.<br />

2. Create a new ile called <strong>Bootstrap</strong>Helpers.cshtml inside the newly created<br />

App_Code folder.<br />

3. Add the following code to the <strong>Bootstrap</strong>Helper.cshtml ile:<br />

@helper PrimaryButtonSmall(string id,string caption)<br />

{<br />

@<br />

caption<br />

}<br />

[ 94 ]

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

Saved successfully!

Ooh no, something went wrong!