Day 5: Bootstrap for the Asp.Net Developer

This is an installment in a 30 day series on Bootstrap and the MVC Framework. To see more, check out Day 0 for an index.

Starting with a blank slate and little direction on where to take things visually is a painful part of web development to overcome, especially for those of us who are in the “design challenged” camp.  The Bootstrap front-end framework takes away a lot of the guessing and rework that head-ends most new projects and establishes a design language to work within, while still providing options for look-and-feel via themes.

While we’ve had a number of options over the years as the Asp.Net templates have evolved, most of them have stuck out like sore, outdated thumbs and rarely would you let them find their way into production. Today, we have a starting point that marries us to a visual style that we can be happy with publishing.

Bootstrap is CSS and JavaScript

You’ll include two resources in a page that you want to build off of Bootstrap, the style sheet and the JavaScript library that make it work.

image

The CSS aspect gives you a stock option with fonts, colors and components that work well together, a responsive layout grid, and the flexibility to completely modify the framework’s default colors, spacing and other variables. You can see how diverse things are at the Bootstrap expo site, and build your own theme variant using the tools online. You can also download freely available themes from various sites on the interwebs.

The JavaScript library introduces a number of behaviors and widgets that augment the design with a user experience that most web surfers are now familiar with when working with alerts, tool tips, tabs buttons and more.

Bootstrap is Also Custom HTML Attributes

The next aspect to be aware of is that the framework relies on several custom HTML attributes to kick up the juice. The JavaScript library looks for these attributes to append functionality, help with layout and behaviors and attach events.

image

The above example, from the docs site, shows how to create a “scroll spy” with no code. Note that all things you can do via attributes can be done with JavaScript as well, so you’re not locked into a model.

What I really like about this approach is that the framework isn’t as opinionated as, say, jQuery UI about how you must go about your business. The attributes are an easy way with minimal code to augment your page.

Bootstrap is Built In

As of version 5, Microsoft has elected to make Bootstrap the framework of choice in every non-blank web application, making it easy to start working with.

image

It’s included in the bundles, configured at app startup, and it’s included on all child pages that leverage the default layout, located in your Views\Shared folder.

Bootstrap is Pretty Easy

Once you get your head around the opinions that Bootstrap does have, you’ll find that creating a toggle button styled in the same way as everything else on your site becomes quite trivial.

image

Of course, there is more to Bootstrap than just toggle buttons, and there is more to the MVC Framework than spitting out static HTML, so we have some work to do to finish exploring this dynamic duo.

Next steps

Tomorrow we’ll look at how we can start to change the way that we render our content, leveraging MVC and the Bootstrap library together.

Day 4: Making a Page Worth a Visit

This is an installment in a 30 day series on Bootstrap and the MVC Framework. To see more, check out Day 0 for an index.

A page instantly becomes more interesting with useful data and a bit of style. Today we’re going to stuff a bit of data into our view and rock it out a little bit with some Bootstrap style.

Introducing Some Data

If you’ve been following along you’ll have a controller called SimpleController with an Index method in it.  I’m going to come back to that in a moment, but first we need a class to store our data in.  Right-click on the Models folder in the solution and select Add –> Class…, then name it Person from the dialog.  Add FirstName, LastName, Birthdate, LikesMusic and Skills (an ICollection of string) properties, so it ends up looking like so:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
    public bool LikesMusic { get; set; }
    public ICollection<string> Skills { get; set; }
}
Those properties should give us some interesting data to look at. Now, return to your Index method on the SimpleController and update the code to do the following:
public ActionResult Index()
{
    var person = new Person
    {
        FirstName = "Billy Jo",
        LastName = "McGuffery",
        BirthDate = new DateTime(1990, 6,1),
        LikesMusic = true,
        Skills = new List<string>() { "Math", "Science", "History" }
    };

    return View(person);
}

We are initializing a new Person object and updating the call to View() to pass in the person object.

Note of Awesome In previous versions of the MVC Framework and Visual Studio, we used to have to build our solution to get the types available to the tooling, this is no longer the case, allowing for a little less back-and-forth and confusion over missing types in the tooling dialogs. A nice new feature!

Scaffolding a View

Now, as nice as that Index page was that we created in the Simple view folder, it’s just got to go! Select it from the Solution Explorer and delete it, then return to your SimpleController code file and create a new view in a similar fashion. This time, however, when you’re creating the view, you’ll need to select the “Details” template and the “Person” class.

image

Now when you run your application and navigate to Simple/Index, you’ll see something like the following:

image

…which is more interesting, but it just doesn’t sing.  We need it to look more like…

image

Bang! Now we’re snapping!  Let’s see how that breaks down.

Bootstrapification

The page is missing some zing  and some data. So we need to fix that. The scaffolder does its best to drop properties on the page, but it doesn’t do so well with collections (without special instructions) and tends to just dump the properties in, more or less, a list. It’s a good place to start and helps get a minimal viable product out the door, but it’s not pretty.

To get the page looking like version 2 above, there are four main components that we need to address. The first is just the setup code for the page, where you set the model type, the page title and collect some information to help render the view.

@model WebApplication29.Models.Person

@{
ViewBag.Title = “Index”;
var likesMusic = Model.LikesMusic ? “active” : null;
var notAMusicFan = !Model.LikesMusic ? “active” : null;
}

Next is three divs, each with a slightly different purpose. The first is the page header, a place to block out some info on the page and relay context.

<div class=”page-header”>
<h1>Welcome to the Person Page <small>Read all about @Model.FirstName</small></h1>
</div>

Then we push out the primary details of the person.

<div>
<h3>@Model.FirstName @Model.LastName</h3>
<p>@Model.FirstName was born on @Model.BirthDate.ToString(“D”).</p>
<p>
<div class=”btn-group” data-toggle=”buttons”>
<label class=”btn btn-success btn-sm @likesMusic”>
<input type=”radio” name=”options” id=”option1”> Likes Music
</label>
<label class=”btn btn-success btn-sm @notAMusicFan”>
<input type=”radio” name=”options” id=”option2”> Suffers in a Distorted Reality
</label>
</div>
</p>
</div>

And finally, we loop through all the skills the person has and set them up as labels.

<div>
<p>
Skills:
@foreach (var skill in Model.Skills)
{
<span class=”label label-primary”>@skill</span>
}
</p>
</div>

Up Next…

Now that we’re looking at pulling some real data into our views, it’s likely a good time to step back and get a feel for what Bootstrap is and how it can help us style our pages. Tomorrow we’ll take a look at what Bootstrap has to offer our UI.

Day 3: Adding a Controller and View

This is an installment in a 30 day series on Bootstrap and the MVC Framework. To see more, check out Day 0 for an index.

When we talk about “adding a page” to a site, what we usually are referring to is setting up some kind of response to a client request. Sometimes that request will be an HTML page, but it might be a dynamically created image, a file built on the fly, or any other HTTP compliant result.

In any case, if the goal is to try to render something that the user is going to see on their screen, we’re likely talking about adding controllers and views.

Creating Controllers

As we already discussed, we will follow the conventions that have been laid out so that we can leverage the built in tooling. To get started, right-click on the Controllers folder in the solution explorer and follow the context menu to “Add –> Controller…”.  This is the process for using the scaffolding exposed by the framework, launching a dialog that prompts you for the information it needs to build out a starting point. There are a number of options, but let’s just look at first one for now: the Empty Controller.

[image_thumb[4]](https://jcblogimages.blob.core.windows.net/img/2014/06/image_thumb4.png)

This gives you a simple option to name a controller when selected.

[image_thumb[7]](https://jcblogimages.blob.core.windows.net/img/2014/06/image_thumb7.png)

I called mine “SimpleController”, which you’ll see has some significance in a moment.  As a class, future James will know exactly what present James means by this name.  Here’s the class that is generated for me.

public class SimpleController : Controller
{
// GET: Simple
public ActionResult Index()
{
return View();
}
}

So, again, this is a class with a method, but we call it a controller with an action. In this case, my Index “action” returns the result of a call to the View method, which is found on my base class that I inherit from (Controller). ActionResult, the return type of Index, is a type located in the MVC Framework that we’ll look Because we’re following convention, the View method will attempt to locate a view named “Index” found in the Views folder, in the Simple subfolder.

Unfortunately, that view doesn’t yet exist. Thankfully, this isn’t hard to do.

Creating Views

In the code editor window, right-click on the Index method (right on the name of the method itself) to invoke the context menu. Select “Add View…” to get the dialog open to create your view.

[image_thumb[10]](https://jcblogimages.blob.core.windows.net/img/2014/06/image_thumb10.png)

The nice thing here is that you don’t have to type in the name of your view. The tooling just assumes the name from the method.

At this point, use the “Empty” template to create your view and select the option to “Use a layout page” as I have above. Leave the name as-is so that we can follow along on that convention gravy train. When you click “Add”, a view file will be created for you with the cshtml (or vbhtml) extension, with something similar to the following code:

@{
ViewBag.Title = “Index”;
}

<h2>Index</h2>

The @{ … } notation is Razor syntax to say, “here’s a code block”. This is used to interact with the rendering of the view and in this case it’s simply setting the value of the page Title in the ViewBag.

With your cursor in the Razor editor, run your application by pressing CTRL+F5 (run without debugger), and navigate to your newly created page. For me, my application started up on port 48995 and the full URL was http://localhost:48995/Simple/Index. You can think of that address as http://host/Controller/View for any page that is following the default convention for routing.

[image_thumb[15]](https://jcblogimages.blob.core.windows.net/img/2014/06/image_thumb15.png)

New page for the win!

Next Steps

A page that says index will really only hold you over for so long, so up next we’ll find out how to send along more meaningful information to our client.

Happy coding! Smile

Day 2: Examining the Solution Structure

This is an installment in a 30 day series on Bootstrap and the MVC Framework. To see more, check out Day 0 for an index.

Now that we’ve had a chance to see what the default project looks like when running, let’s talk about the parts of the project that make it happen. We talked briefly about controllers, actions and views, so let’s figure out where those come from first before moving on to other important contributors to our project.

Controllers and Views, and Actions, Too

One of the things that the MVC Frameworks does reasonably well is to follow convention over configuration. That means that with very little effort you can make use of most of the features of the framework without having to set XML, change project configuration or the like…it just “works” out-of-box. Of course, this means that it is also fairly reasonable to assume that it is somewhat opinionated, especially when it comes to tooling. So, there are “right” ways and “choose your own pain” ways to approach development.

Thankfully, controllers and views are easy pieces, you can find them in the apt-named folders, “Controllers” and “Views”, respectfully and consistently across most projects.

image

Each controller has a corresponding folder inside of Views to help keep things organized further. If you’re generating views from the built-in tooling, they are created here as well. As the MVC Framework tries to find the view you would like rendered it checks here first and then falls back to the “shared” folder, also part of convention.

A controller is just a class and actions are just methods. This is an important detail, so keep that in mind as you develop. While you can use either version of either word and be correct, you’ll gain the favor of the lexicon if you try to use the terms as they are known in the framework. Other extension points, for example, reference these terms and they are good cues to help other developers (including the future version of you) survive your code down the road.

A view is typically HTML plus some optional code written using the Razor syntax. We don’t create “web pages” any more, we create applications. The view engine – Razor – using your view files and any supplied data to assemble and output HTML, which is returned to the client who initiated the request.

Of special note is the Shared folder under Views, where you’ll find the layout file (_Layout.cshtml) that is used as a template or “master page” for your site, giving you a way to have pages that follow a similar look-and-feel without having to repeat the same layout instructions on each page.

Models

These guys are pretty easy: they are just classes. Models will have properties and helper methods. They may reflect data that is stored in the database, data that you wish to store in the database, or input from users. They may store options for users to choose from when inputting their data. There are a lot of things Models can be, but for the most part they are just plain old CLR objects (POCOs).

Where things get interesting is when you “pass” a model to a view, allowing an HTML page to be rendered based on the properties of the information contained therein.

Scripts, Content and Fonts

Any web project is driven by a set of static or semi-dynamic resources such as CSS files, images, fonts and JavaScript sources. The solution gives you some basic structure to help keep these organized, but these are not contributors to the MVC project structure and they do not influence the framework. You are free to rename these and organize these types of files as you wish.

The one caveat would be that the default template (mostly driven from your application startup files) does make use of this structure, as do some of the startup components. If you start to move these around, you’ll also need to update those aspects of your project.

In these folders you’ll find the requisite pieces needed to ship a web site that reflects the Bootstrap design language, namely jQuery, the Bootstrap library and stylesheet, the glyphicons font and a few libraries to assist with browser incompatibilities and functionality polyfills to add capabilities that are missing in out-of-date or non-compliant browsers.

Application Building Blocks

imageThe App_Start folder is likely the most interesting from a code perspective as it provides the wiring to pull your application together. Bundles are a way to reduce and compress script and style resources in a non-lossy fashion (as far as the browser is concerned). Filters allow you to modify the execution pipeline of your application. Identity is the implementation of the built-in local user account manager. Routing allows friendly URLs and custom mapping of resources. And the Startup.Auth file (a partial class) is used to tell your app which types of user identies you’ll be using to pair with your local user accounts.

There’s a lot in that last little paragraph, but we’ll unpack it as we go.

The Root of all Web

We wouldn’t be complete if we didn’t cover all the bits, including those in the root of our application.

At the top of the solution explorer you’ll see “Properties” and “References”, standard in all .Net applications. These give you access to things like assembly information, the built-in web server configuration and references to external dependencies that you take.

Towards the bottom of the list you’ll see a couple of files that are common on all Asp.Net sites, Global.asax and Web.Config. These give instructions to the MVC Framework, to the Asp.Net runtimes and to IIS itself as to how to execute requests and make use of resources. They allow you to store settings and provide values to libraries and assemblies you might be using. You’ll note that Global’s startup method calls out to some of the startup classes we covered in the last section as well.

image

Favicon.ico is the image that will be displayed in a browser tab when someone visits your site.

Packages.config is a list of all the packages that are required by your application. If you open  a project and do not have these packages installed, Visual Studio will go and fetch them for you when you try to build.

There’s one last class in there, a file named Startup.cs, which configures the authentication bits via a call to the Configure method in our Startup.Auth partial class. This one is interesting because it leverages an OwinStartupAttribute to get invoked before anything else in our app is executed. OWIN is a bigger topic that we’ll review later in this series.

Next Steps

Now that we have the lay of the land, tomorrow we’ll add a new page to our application so we can see a little more of the plumbing in play.

Happy coding!

Day 1: The MVC 5 Starter Project

This is an installment in a 30 day series on Bootstrap and the MVC Framework. To see more, check out Day 0 for an index.

Getting started in MVC is the easiest it’s ever been, and it’s even easier to look good doing it. Rather than building up yet another short-lived, likely passing design, Microsoft made another nod to open source software and adopted the Bootstrap library as a design language. We’ll get to all those bits shortly, but for now let’s see what happens when you get started in MVC 5.

First off, select File –> New Project from the Visual Studio 2013 menu.  If you select the “Web” category you’ll see only one type of project, an “Asp.Net Web Application”. All web projects have been consolidated under the “One Asp.Net” banner, so the project type is an easy selection. The next dialog that pops up gets a little more interesting:

image

You’ll note that there are a few more options here. Click around on the project templates to see the description (we’re going to be focusing here on MVC). The notable options outside of your template selection are the Authentication, Core References and Azure options.

Authentication – If you’re targeting a general web audience you’ll likely want to make use of Individual User Accounts (the default), which opens the door for you to integrate with 3rd party providers such as Microsoft, Facebook, Twitter and Google. If this isn’t the route for you, click through and read about each of the other types.

Core References – With the removal of project type GUIDs came the arrival of much less hacking to get different types of web projects working in the same solution. You can now easily put Web Forms, MVC and Web API all in the same project. Also here is your ability to add a test project.

Windows Azure – This is the part I like, streamlined deployment baked directly into the project creation. While you can always change these options or even add them later, for those of you who have an Azure account, this is an easy way to get code running quickly in the cloud. If you don’t have an account, it’s easy to set one up.

Running the Project

Well, don’t wait! Just run the site! You’ll land on a welcome page (just a static HTML page in your project) but you can hit CTRL+F5 to see your wonderful new digital bits running locally.

image

Bang. You got yourself a web site. Let’s pause to consider what’s going on.

The page that is delivered to the browser is straight HTML – image, script, p tags and all. In a nutshell, here’s how that content gets rendered to the client:

  • A request for a specific resource (a page, in this case) hits the server and comes into the pipeline.
  • A controller is selected, based on the routing configuration.
  • Any dependencies for the controller are resolved and the controller is instantiated.
  • Any payload from the request – form content, query string – is evaluated to see if it can be used to provide parameters for the method (action) that will be executed.
  • The MVC Framework finds the most appropriate action to call based on the payload and method (POST, GET for example) of the request.
  • The method is invoked, passing in the discovered parameters.
  • The information you need (if any) is passed through to Razor, the default view engine.
  • Razor prepares to render the CSHTML file (or VBHTML file) as requested by the framework using anything that was built up so far.
  • Rendering occurs, which often and typically includes a “layout” or master page that is wrapped around the entire content.
  • Happiness ensues.

There are actually a few more moving parts involved in the request as we’ll see in the coming weeks, and we haven’t even talked about application startup yet. The framework also provides a number of ways to intercept requests and participate in the executing pipeline, so we’ll cover that as well as the month unfolds.

On day 2, we’ll breakdown the solution that was created and start twiddling some bits. See you tomorrow and happy coding!

Day 0: Bootstrapping Mvc for the Next 30 Days

In the coming weeks you’ll see a wide range of topics, tips, tricks and the ins-and-outs of working with the Bootstrap library and CSS framework with Asp.Net’s MVC Framework.  This page will serve as the curated index of all posts for the month.

These posts will focus on using three key bits that are pre-requisites for the month: Visual Studio 2013, MVC 5 and Bootstrap.  Along the way we’re going to make use of jQuery and even have a look at leveraging Knockout.js to make the client development a little less mundane.

Expect to start simple but be ready for a daily dose of content, presumably with something new for you each day, or at least a new twist on something you might be familiar with. Bring your  willingness to try a bit of code, and I’ll try to bring some awesome.

Shameless plug: If you’re looking for professionally designed themes to replace your palette, you can help out this blogger (me!) by purchasing one over at {wrap}bootstrap. They have a selection of great looking Bootstrap themes. A very affordable alternative to taking the time to create your own theme. Check out Day 23 for more information on creating a site where users can choose which theme they see.

I’m assuming you’re a dev with some web experience. I’ll try to include some helpful links where content might be new or if questions come up. Thanks for joining along!

The 30 Day Breakdown

Warming Up

Enhancing Our Views

####

Exploring Bootstrap

Special Announcement!

Adding Some Sparkle

So, You’ve Got People Logging In

Wrapping Up With Some More Bootstrap

If you’d like a copy of the completed project, please be sure to check out the repo with the final version of this series’ code on GitHub.

Happy Coding!