Day 30: Loading Bootstrap Modal Content via AJAX

This is the final installment in a 30 day series on Bootstrap and the MVC Framework. To see the rest of the series be sure to check out Day 0 for an index. I hope you have enjoyed following along! Smile

Here in our last post in the series we’re going to revisit our modal dialog confirmation box that pops up when a user tries to delete a record. At this point, regardless of the notification selected for delete, the user will see the same static dialog.

Loading Remote Content With Bootstrap’s Modal

There is built-in support for Bootstrap to load content into a modal, but there are some limitations. First, Bootstrap loads the content the first time the constructor is called on the modal. Secondly, the modal’s constructor is only ever called once, meaning, you can’t refresh the content without some extra script.

Rather than trying to put a square peg in a round hole, we can take the simpler approach of just loading the content with jQuery. After all, it’s clean, easy to understand, and at the end of the day the modal is just HTML.

This approach will work better for us for the following use case:

  • User selects to delete a notification
  • They cancel out of the dialog
  • The select a different notification to delete

At this point, the remote loading capabilities of Bootstrap’s modal break down and we’d have to get into hacky stuff that may not survive a minor version upgrade. Pass! In my opinion, the modal should have an overload that accepts a ‘remote url’ parameter.

If, however, you have a use case that doesn’t involve refreshing the dialog, I encourage you to check out the docs for using the built-in functionality.

Improving our Delete Confirmation

Rather than just giving a generic message, we’re going to instead load some content via AJAX. This will give us a chance to put a visual preview of the data that will be deleted in front of the user.

image

To accomplish this we’re going to need to make small change to our modal markup (in Views\Account\_RenderNotifications.Modal.cshtml), as follows:

<div class="modal-body" id="notificationPreview">
    <p>Loading content...</p>
</div>

What I’ve done here is removed the content from the modal-body section of the markup and replaced it with a loading message.  I’ve also given the DIV an ID so that we can address it from JavaScript more directly.  Also, revisit your Views\Account\_RenderNotifications.js.cshtml and update the confirmDelete method, as we’re now going to clear the contents and load the text dynamically.

function confirmDelete(id) {
    currentNotificationId = id;
    previewContainer.html('<p>Loading content...</p>');
    previewContainer.load(confirmUrl, { id: currentNotificationId });
    $('#deleteConfirmModal').modal('show');
}

To pull that all together we need a couple more variable declarations at the top of the script. Here’s my final list of vars:

var readUrl = '@Url.Action("MarkNotificationAsRead")';
var deleteUrl = '@Url.Action("Delete")';
var confirmUrl = '@Url.Action("GetNotification")';
var previewContainer = $('#deleteConfirmModal #notificationPreview');
var currentNotificationId;

You’ll notice that I have added a confirm URL and captured the element (in previewContainer) that we are using for the confirm. This saves me from having to requery the DOM on each display of the dialog.

Adding the Controller Action

We’re going to use that same pattern for loading up the notification for the confirmation that we used for modifying and deleting. Let’s add a GetNotification method to our AccountController that has the following code:

public ActionResult GetNotification(int id)
{
    var userNotification = GetUserNotifications().FirstOrDefault(n => n.NotificationId == id);

    if (userNotification == null)
    {
        return new HttpNotFoundResult();
    }

    return PartialView("_RenderNotifications.ModalPreview", userNotification);
}

This time, we’ll be returning a partial view, as indicated in the code above, that will help us render the relevant content for the user to make their choice.

But hey…that code to load a single notification for the logged in user is crying for some refactoring, am I right?

Adding the Partial View

The controller is wired to pass the single notification to a partial view, which will essentially have the same information we had in the content section of the modal markup, but now we’ll also render in some notification-specific information. You can use your imagination on how this could be further extended with more complex objects in your own project.

Here are the contents of _RenderNotifications.ModalPreview.cshtml, which you should put into Views\Account:

@model SimpleSite.Models.Notification

<p>You have selected to delete this notification.</p>
<p>
    <div class="panel panel-warning">
        <div class="panel-heading">
            <h4>@Model.Title</h4>
        </div>
        <div class="panel-body">
            If this was the action that you wanted to do,
            please confirm your choice, or cancel and return
            to the page.
        </div>
    </div>
</p>

Next Steps

Wow! Thirty days of Bootstrap and MVC! It’s been a long 30 days…50 days actually, but no one could have foreseen the passing of my Grandma, my three-day fever of 103 degrees or the fact that this would end up running into my vacation for my 14th wedding anniversary and a most excellent trip to Seattle with my high school sweetheart (to whom I am married).

I have a few more things to add to this series, but for now we’ll call it a wrap. Thanks for your questions, suggestions, feedback and comments along the way!

Happy coding! Smile

Day 29: Confirmation Dialogs for Delete Actions

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.

We just gave our users the ability to delete a record from the database in Day 28, but a single click does the deed without confirmation. It would likely be better to at least give them a little prompt to confirm that this is what they were trying to do in the first place.

image

Let’s first talk about how dialogs are composed and how to display them in a page.

Bootstrap Modal Dialogs

Modals are made up of a wrapper, an outer and inner container and three common sections that provide default styling and handle proper rendering: the header, the body and the footer. You can represent the basic structure of the modal as follows:

<div class="modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">...</div>
            <div class="modal-body">...</div>
            <div class="modal-footer">...</div>
        </div>
    </div>
</div>

You can show a dialog by using a button with an attribute that Bootstrap is aware of:

<button class="btn" data-toggle="modal" data-target="#theModal">
  Show my modal
</button>

Or you can invoke the modal by calling it from JavaScript:

$('#deleteConfirmModal').modal('show');

For other events, defaults and other JavaScript method calls that are available, be sure to check out the docs on the Bootstrap site.

When using modals you’ll want as little interference as possible with the styles and layout of the elements being used, so the recommendation is to put the container for the modal as close to the root of the document structure as possible.

One thing that I’ve run into when using the button approach is the need to have the CSS selector on the data-target attribute (see the code above). I’m not sure why this is the approach, but if you forget that you need the hashtag as a prefix to the ID, your modal won’t display. Regardless, we’re going to be using JavaScript to do our work today, but keep that tip in mind as you start working with this on  your own.

The Game Plan

For this exercise we’re going to hit a couple of areas of the project, so here’s a quick checklist if you want to follow along. We’re going to:

  • Clean up our JavaScript and put it in a separate file
  • Add an optionally rendered section to our _Layout page
  • Add a partial view for the markup needed for our dialog
  • Update the Manage view to include our new bits

Some Cleanup, Some JavaScript

We’re going to start growing our client-side scripts on the view that renders notifications a little and one thing I like to do is to keep those bits organized. The JavaScript we have so far to give some UX for notifications is in our _RenderNotifications partial view, which presents some limitations as to when script can execute and whether or not jQuery has been loaded.

One easy way to keep these things straight, and organized in our project, is to add a _PartialViewName.js.cshtml file to our project in the same folder as our view. We can then consider the JavaScript related to the view as another asset that needs to be loaded on the full view.

So let’s do that. Add a new view to the Views\Account folder called _RenderNotificationsjs. If you use the scaffolding tools, you’ll notice that you can’t properly name it (it complains about invalid characters), so add it as I’ve shown, then rename it to _RenderNotifications.js.cshtml once the file is there.  Next, remove the old JavaScript from the _RenderNotifications.cshtml and put it in the new .js.cshtml file.

<script type="text/javascript">
    
    var readUrl = '@Url.Action("MarkNotificationAsRead")';
    var deleteUrl = '@Url.Action("Delete")';
    var currentNotificationId;

    function updateNotification(id, action) {
        $("#notificationFormItemId").val(id);
        switch (action) {
        case 'read':
            $("#notificationForm").attr('action', readUrl).submit();
            break;
        case 'delete':
            $("#notificationForm").attr('action', deleteUrl).submit();
            break;
        default:
            console.debug('Unknown action ' + action);
        }
    }

    function confirmDelete(id) {
        currentNotificationId = id;
        $('#deleteConfirmModal').modal('show');
    }

    $(function() {
        $("#deleteConfirmModal").on('click', "#deleteConfirm", function() {
            updateNotification(currentNotificationId, 'delete');
        });
    });

</script>

Remember that .cshtml gives us a little more power than just a straight .js file. We can do things like interact with the ViewBag or the page Model, write code that is parsed by Razor and make use of Html helper methods, all of which can be quite handy.

There’s not too much more going on here than there was before, except that now we capture the ID of the notification in our confirmDelete method, and we are wiring up a click handler for the modal dialog that we’re going to implement.

One final thing to do on our partial is to update the Delete button (the A tag) to call our new JavaScript method as follows:

<a href="javascript:confirmDelete(@notification.NotificationId)">Delete</a>

Rendering at the Root Using Optional Sections in our Layout

Remember the note about keeping the modal as close to the document root as possible? Well, there’s a problem there when we’re down at the view or partial view layer, stuck inside our other “main content” area of the page. We’re inside all these other containers already and we can’t break out without a little help from the MVC Framework.  What we want to do is to add another optional section, much like the scripts section. We can call this topLevel for now, though you’d likely want it to be more meaningful in a real project.  Add the following code to your _Layout file.

@RenderSection("topLevel", required: false)

It should appear right after the BODY tag, first thing in the document, like this.

image

Now, whenever you have something that will be injected from a view into the page in this topLevel section, you will be able to put elements directly into the root of the document.

Create the Modal Partial

Next up, we’re going to create a _RenderNotification.Modal.cshtml partial view that has the HTML for our modal in it. This will help to keep our core view simple, and keep our related files together in our project.  The markup for the modal follows the same basic structure I highlighted above and adds a few other elements to the mix.

<div class="modal fade" id="deleteConfirmModal" tabindex="-1" role="dialog" aria-labelledby="deleteLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="deleteLabel">Deleting a Notification</h4>
            </div>
            <div class="modal-body">
                <p>You have selected to delete this notification.</p>
                <p>
                    If this was the action that you wanted to do,
                    please confirm your choice, or cancel and return
                    to the page.
                </p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="deleteConfirm">Delete Notification</button>
            </div>
        </div>
    </div>
</div>

There’s a class ‘fade’ in there that tells bootstrap to slide and fade the modal in from the top. There are a few ARIA attributes in there for accessibility.  I’ve added a title to the header, content in the body and buttons to either dismiss the dialog (cancelling the delete) or to confirm the operation when the user elects to delete the notification.

Perhaps the most interesting bit in there is the data-dismiss attribute on the cancel button, which tells Bootstrap that this dialog can be hidden when the button is clicked.

Updating Our View

Finally, we update our view, adding the modal to the page and including the JavaScript that we need to pull it all together.

At the bottom of Manage.cshtml in Views\Account we add the topLevel section to the view and in it we render the modal markup from the partial view we created.

@section topLevel{

    @{ Html.RenderPartial("_RenderNotifications.Modal"); }

}

Immediately after that, we update our scripts section to include the JS we need and created above.

@section Scripts { 

    @Scripts.Render("~/bundles/jqueryval") 
    @{ Html.RenderPartial("_RenderNotifications.js"); }

}

Because we’ve kept things fairly organized along the way, changes to our view are minimal but at the same time we’re able to improve the user experience a fair bit. We’ve added an easy way to get content into the root of our document and simplified our partial views. And look…

image

…we even managed to keep our related files in one place in the solution explorer. 

Next Steps

Our delete is now protected by the dialog, but we’d like to give the user a better picture of what it is they are deleting from the database. Tomorrow, in our last post in the series, we’ll look at wiring up the dialog box to load contents via AJAX.

Day 28: Doing More Interesting Things With Buttons

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.

Using the styling of Bootstrap or a replacement theme is a great way to make your site stand out, and buttons are a great example of making the UI more rich and friendly to users. They are likely the first thing you’d write some CSS for if you were starting from scratch on your site, so the tweaks and highlights they offer out-of-box are quite welcome.

Basic Buttons

If you don’t style your buttons, they’re going to kinda suck. Well…it’s not that they won’t work or anything, but you will just get the boring old browser-styled version of a button.

image

And because each browser has it’s own default stylesheet, you can’t be guaranteed that any user will see the same font, layout or spacing. Thankfully, enforcing these attributes across clients is only an attribute away.

<button type="button" class="btn btn-primary btn-sm">A button</button>
<button type="button" class="btn btn-success btn-sm">Another button</button>

You’ll notice that I used the btn-sm class in the source above, there are large (btn-lg), regular (no class needed), small (btn-sm) and extra-small (btn-xs) to choose from. And now my buttons look like so, in every browser:

image

If I want them to be the same width, I can also use the grid system for sizing, dropping, say, a col-md-4 into the class attribute to get the following result:

image

Grouping Things Together

The buttons look better now, but they’re bumping up against each other. They’d look better still if they looked like they were part of the same control group. We can assemble buttons into groups by providing a touch more markup to the elements, as seen below, with a simple DIV wrapper.

<div class="btn-group">
    <!-- buttons here -->
</div>

image

I changed the text here because this is the code that I’ll be working into my partial for the notifications.  I also made the buttons the same color – from a design stand point I think it looks better (and, heck, I’m even color blind) – and I removed the grid sizing on the buttons to allow them to group properly without having to add custom CSS styles.

Putting Some Fancy On

Chances are we could get away here with the two buttons side-by-each, but in the event that we need to add more actions the page is going to start to get a little wide. An improvement we can make here is to give the users a default action, but then to put the rest of the less-commonly accessed actions into a dropdown to look like this:

image

This is called a split button dropdown, where a clickable action is available and additional commands are tucked into the drop down. Rather than wrapping the buttons in just a DIV, we also introduce a caret for the dropdown and have a UL to act as a container for the non-visible actions.

<div class="btn-group">
    <button type="button" class="btn btn-success btn-sm">Mark as Read</button>
    <button type="button" class="btn btn-success btn-sm dropdown-toggle" data-toggle="dropdown">
        <span class="caret"></span>
        <span class="sr-only">Toggle Dropdown</span>
    </button>
    <ul class="dropdown-menu" role="menu">
        <li><a href="#">Delete</a></li>
        <li><a href="#">Send SMS</a></li>
        <li><a href="#">Make cheese</a></li>
        <li class="divider"></li>
        <li><a href="#">Baz</a></li>
    </ul>
</div>

I’ve added in the correct attributes on the caret button element – namely the data toggle – so that it plays properly with the framework. Per the documentation, I’ve also added an sr-only class that allows screen readers to make sense of the control grouping. The inner commands are now simply anchor tags and don’t require any of the button classes.

So, there all-of-a-sudden seems to be a lot going on there, but let’s break down the basic structure:

  • A DIV to group everything together
  • A BUTTON for the main action
  • A BUTTON for the caret (dropdown)
  • A UL with a list of LIs for the additional commands.

The skeleton looks like this:

<div class="btn-group">
    <button type="button" class="btn">Primary Action</button>
    <button type="button" class="btn dropdown-toggle" data-toggle="dropdown">
        <span class="caret"></span>
        <span class="sr-only">Toggle Dropdown</span>
    </button>
    <ul class="dropdown-menu" role="menu">
        <li><a href="#">...</a></li>
        <li><a href="#">...</a></li>
    </ul>
</div>

One final note: You would correctly assume, were you the assuming type, that the drop down functionality requires the JS library to work (which is already included in our web site bundle and layout).

Updating our View

Now, forget what we’ve done so far in the TD for our actions. We’re going to change it up a bit and get things properly in line for some real-world action.

Since we’re going to be changing data we are going to want to do a POST back to the server, so we have the option of using the Html.BeginForm helper.  But generating a series of forms representing all actions for all notifications could get complicated quite quickly (in other words, we don’t want a form for each action, for each notification). Instead, we need to decorate our split buttons with the appropriate IDs, then put together a bit of JavaScript to do the submit for us on a single, static form. The form contains a hidden input for the ID and will be at the end of the document in _RenderNotifications, followed by the related JavaScript:

<form id="notificationForm" method="POST"><input type="hidden" name="id" id="notificationFormItemId" /></form>

<script type="text/javascript">
    
    var readUrl = '@Url.Action("MarkNotificationAsRead")';
    var deleteUrl = '@Url.Action("Delete")';
    
    function updateNotification(id, action) {
        $("#notificationFormItemId").val(id);
        switch (action) {
            case 'read':
                $("#notificationForm").attr('action', readUrl).submit();
                break;
            case 'delete':
                $("#notificationForm").attr('action', deleteUrl).submit();
                break;
            default:
                console.debug('Unknown action ' + action);
        }
    }
    
</script>

Here we are using the URL helper method to resolve the URLs needed for read and delete actions.  The JavaScript simply accepts the ID and an action parameter, then sets up the form correctly and submits it.

Next, skip back up the document a little to the TD that contains our split button. We’ll replace the entire contents of the TD with the following:

<div class="btn-group">
    <a class="btn btn-success btn-sm" href="javascript:updateNotification(@notification.NotificationId, 'read')">Mark as Read</a>
    <button type="button" class="btn btn-success btn-sm dropdown-toggle" data-toggle="dropdown">
        <span class="caret"></span>
        <span class="sr-only">Toggle Dropdown</span>
    </button>
    <ul class="dropdown-menu" role="menu">
        <li>
            <a href="javascript:updateNotification(@notification.NotificationId, 'delete')">Delete</a>
        </li>
        <li><a href="#">Send SMS</a></li>
        <li><a href="#">Make cheese</a></li>
        <li class="divider"></li>
        <li><a href="#">Baz</a></li>
    </ul>
</div>

You’ll notice that our A tags are now just invoking our JavaScript method, passing in the notification ID of the current record (remember that we’re in that outer foreach loop here). We can continue to develop new methods by wiring up the A tag and extending the switch statement should we like.

A Couple of Controller Methods

Finally we’re going to need to wire up our controller to catch those user actions and do the dirty bits. Marking the notification as viewed will be first. We’ll use the DB context to retrieve, update and save the selected record, so we’ll make a small change to the way we initiate the DB context and move it to a class-level declaration as such:

private readonly SiteDataContext _context = new SiteDataContext();

Remember to remove the following line of code from the GetUserNotifications method and update all occurrences of context to _context (your code won’t compile if you don’t).

[HttpPost]
public ActionResult MarkNotificationAsRead(int id)
{
    var userNotification = GetUserNotifications().FirstOrDefault(n=>n.NotificationId == id);

    if (userNotification == null)
    {
        return new HttpNotFoundResult();
    }

    userNotification.IsDismissed = true;
    _context.SaveChanges();

    return RedirectToAction("Manage");
}

Similarly, the code for the delete action will use the same DB context to delete the requested record.

[HttpPost]
public ActionResult Delete(int id)
{
    var userNotification = GetUserNotifications().FirstOrDefault(n => n.NotificationId == id);

    if (userNotification == null)
    {
        return new HttpNotFoundResult();
    }

    _context.Notifications.Remove(userNotification);
    _context.SaveChanges();

    return RedirectToAction("Manage");
}

There are a couple of quick notes here that I should mention. From a security standpoint we’re doing some good things, namely, we’re using a common method to only load into scope the notifications of the currently logged in user. We’re leveraging the fact that the framework provides a mechanism to correctly provide the user’s identity and limiting the user’s request to only allow execution of modifying or deleting records in a “row-level” security kind of way. Our controller is marked with the Authorize attribute, so if we couple this with SSL we’d be in pretty good shape.

Then there’s the bits that aren’t really good practice, but are good enough for the point of this exercise. First, we’ve got this GetUserNotifications method on the AccountController class.  What about “AccountController” says anything about “loading the notifications for a specific user”? Nothing, right? This data access, as I’ve mentioned before, should be pushed into a repository that makes use of the DB context through a Dependency Injection mechanism that only creates one instance of the DB context per request. And, the controller should take that repository through DI.  This would make things more flexible (why write data access in more than one spot) and testable (we could use mocks to test more easily).

Next Steps

Certainly you wouldn’t want your users deleting data without confirmation (if at all), so in the next installment we’ll have a look at putting a dialog in place to ensure users are invoking the intended action.

Day 27: Rendering Data in a Bootstrap Table

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.

We created a nice tab for our users to be able to manage the different components of their account, hi-jacking the Manage Account feature of the default MVC template. Now we want to render the user’s outstanding notifications in a good looking table in one of those tabs.

Caution: this is the lipstick on a pig post of the series. Here be dragons…

Rendering Tables with Bootstrap

The first thing you need to know is that you don’t have to throw away a single thing you’ve learned in your years of HTML ninja skill building. Tables are still not to be used for layout. Tables are for lists of data. And more importantly, Bootstrap doesn’t try to change the semantics or document structure for a table. In fact, to get the Bootstrap look-and-feel in an HTML table, you need to apply but one class.

<table class="table">
  ...
</table>

So what else does it offer?  A bunch of common things that you might try to do, like “tighter” versions of a table, striped styling or hover-states. You can also use the now familiar contextual classes on rows or cells to highlight pertinent information to your users.

All in all, it’s a clean looking table that will suit most needs and fit in with the rest of the site.

image

Another important aspect of the Bootstrap table is the ability to easily make a table responsive. I don’t have the answer as to why this isn’t the default, but it’s easily added with a DIV wrapper that has the table-responsive class. This adds horizontal scroll bars to your tables, when needed, when they are viewed on smaller screens to ensure that the data doesn’t end up in some non-accessible, off-device part of the screen.

image

That wrapper looks like the following:

<div class="table-responsive">
    <table class="table table-striped ">
       <!-- table rows here -->
    </table>
</div>

Retrieving the Notifications

We’re going to need to get the list of notifications that haven’t yet been dismissed. You may have already created some test data with the efforts from the past few days, and that will work great here.

Open the AccountController.cs class and navigate down to the Manage action.  Just before it, add the following code :

private IEnumerable<Notification> GetUserNotifications()
{
    // get the user ID
    var userId = User.Identity.GetUserId();

    // load our notifications
    var context = new SiteDataContext();
    var notifications = context.Notifications
        .Where(n => n.UserId == userId)
        .Where(n => !n.IsDismissed)
        .Select(n => n)
        .ToList();
    return notifications;
}

All this guy is doing, really, is snapping up the rows for this currently logged in user.

One thing to mention here is that we’re really now crying for some Dependency Injection. Our NotificationFilter and our AccountController are now both creating instances of our SiteDataContext – now multiple instances per request – and it’s making our code harder to test.

Adding the Data to Our ViewBag

Both the GET and POST versions of Manage are already relying on ViewBag to get data up to the view, so we’ll follow the same cue and put our notifications in there. In both methods you’ll find the ReturnUrl being assigned to a ViewBag property, so immediately after that, add the following line of code:

ViewBag.NotificationList = GetUserNotifications();

Adding a Partial View for the Table

Next, let’s get a partial view added called “_RenderNotifications.cshtml”.  The model type for the page will be a IEnumerable<Notification>, and we’ll iterate over the collection of rows to generate the TR and relevant TDs inside each of those. The entire view will look something like this:

@using SimpleSite.Models
@model IEnumerable<Notification>

<div class="table-responsive">
    <table class="table table-striped ">
        <tr>
            <th>Type</th>
            <th>Notification</th>
            <th>Actions</th>
        </tr>
        @foreach (var notification in Model)
        {
            var badgeClass = NotificationType.Email == notification.NotificationType
                ? "label-success"
                : "label-info";
            <tr>
                <td><span class="label @badgeClass">@notification.NotificationType</span></td>
                <td>@notification.Title</td>
                <td></td>
            </tr>
        }
    </table>
</div>

There’s a placeholder in there for “Actions”, which we’ll look at tomorrow when we revisit buttons and explore drop-downs.

Updating our Manage View

With the partial view in place and the data being loaded into the ViewBag we’re ready to update our view. Return to the Manage.cshtml file and locate our placeholder for the notifications. Update it to render the partial view, passing in the collection of notifications.

<div class="tab-pane active" id="notifications">
    @Html.Partial("_RenderNotifications", ViewBag.NotificationList as IEnumerable<Notification>)
</div>

That should be it! I found what seems to be a bug in Bootstrap where if you have a table in a tab, and the tab is set to active and you have the fade class, the table doesn’t seem to be visible on page load. It shows up fine after clicking on a tab, but to work around this you’ll notice that I’ve removed the fade class from the tab.

Oh Noes! It’s Turned Into A Mess!

Folks, I’m not going to lie; though the Account controller and Manage views may have never have been intended to handle our humble little notifications, I found several things in both the controller and related views that left me uncomfortable with the design. I’m trying to keep this as a “how to get some MVC in your Bootstrap” type series, but all of the following were worth noting as things I’d try to avoid:

  • Nested views with non-obvious dependencies
  • Multiple methods that do the same work as each other
  • Magic strings
  • Methods doing too many things or things that you wouldn’t attribute of them by their name (for example, the “Manage” action which resolves status messages based on optional parameters)
  • ViewBag use that gets in the way of the view’s maintainability
  • Views that don’t leverage Bootstrap enough
  • Way too much reliance on ViewBag, and, therefore,
  • Absence of reasonable view models
  • Dogs and cats playing together

I will perhaps one day sit down and hash through the AccountController, but needless to say, there’s some amount of work to be done! I, for one, would like to see more best practices in place, a more referencable example of how to do things and sample views that better embrace the Bootstrap visuals (since, after all, it’s included by default in the template).

Now on our end, we’ve done some off-script things as well, namely putting direct database access in a controller (and filter),  pushing database models directly up to the view and leaning on those ViewBag properties to shuffle data around. So, yes, kettle, meet teapot.

All of these things are leading up to another set of posts on best practices Smile.

Next Steps

Okay, our users can now see the list of notifications that are outstanding, but they have no way to manage them just yet. Tomorrow we’ll get some drop-down button action in play and explore some of the ways we can compose some pushable UI.

Day 26: Bootstrap Tabs for Managing Accounts

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.

We’ve got this notification thing going on now and we’d like to give users a way to review notifications. There’s a fairly acceptable landing spot on the “Manage Account” view (at /Account/Manage in your browser), at least for the purpose of these exercises, so we’ll flesh things out there.

However, the view is isn’t really set up for notifications (it’s truthfully not the best spot) so we’ll need to give us some UI to make it work.

Understanding the Tab Component

There are two main elements you’ll need to get the tabs going correctly, a UL tag that will set up as the menu elements, and a DIV to act as a container for the content.

<ul class="nav nav-tabs" role="tablist" id="accountTab">
  <!-- content -->
</ul>

<div class="tab-content">
  <!-- content -->
</div>

Visually, you can link those elements as illustrated below:

image

Because our site includes the JavaScript library for Bootstrap our tabs will automatically render and behave correctly. The classes help with the visuals, and the JS takes care of the behavior.

The UL will contain LI elements for each tab that you wish to display on the page. For us, that will the notifications, linked accounts and password reset. Those last two are the content that already exists on the page at \Views\Account\Manage.cshtml, and the notifications bits are what we’ll fill in after our tabs are in place.

In addition to those two root elements, you can use a bit of JavaScript to manipulate the tabs if needed. For example, if you wanted a particular tab displayed on page load, you could use the ID as part of a jQuery selector and call the show method as follows:

$('#accountTab a[href="#linkedAccounts"]').tab('show');

The DIV for content will in turn hold container elements for the rest of the content you want on the page. The structure will look something like this:

<div class="tab-content">
    <div class="tab-pane active" id="notifications">
        <!-- content -->
    </div>
    <div class="tab-pane" id="linkedAccounts">
        <!-- content -->
    </div>
    <div class="tab-pane" id="passwordReset">
        <!-- content -->
    </div>
</div>

Each of the tab-pane DIVs could also have a fade class applied, which creates a nice content-switching visual. Let’s use that.

Updating the View

If you haven’t done so already, open up the \Views\Account\Manage.cshtml file and start cutting it up! Inside the DIV.row DIV.col-md-12 structure, add the UL for the tab headers, and add a DIV to contain the tab pages including a placeholder for notifications, and the DIVs for linked accounts and password reset. Move the content from those parts of the page in.

The final page code should be similar to the following:

@using SimpleSite.Models;
@using Microsoft.AspNet.Identity;
@{
    ViewBag.Title = "Manage Account";
}

<h2>@ViewBag.Title.</h2>

<div class="row">
    <div class="col-md-12">
        <p class="text-success">@ViewBag.StatusMessage</p>

        <ul class="nav nav-tabs" role="tablist" id="accountTab">
            <li class="active"><a href="#notifications" role="tab" data-toggle="tab">Notifications</a></li>
            <li><a href="#linkedAccounts" role="tab" data-toggle="tab">Linked Accounts</a></li>
            <li><a href="#passwordReset" role="tab" data-toggle="tab">Password Reset</a></li>
        </ul>

        <div class="tab-content">
            <div class="tab-pane fade active" id="notifications">
                <p>Here's where we'll put our notifications.</p>
            </div>
            <div class="tab-pane fade" id="linkedAccounts">
                <section id="externalLogins">
                    @Html.Action("RemoveAccountList")
                    @Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel { Action = "LinkLogin", ReturnUrl = ViewBag.ReturnUrl })
                </section>
            </div>
            <div class="tab-pane fade" id="passwordReset">
                @if (ViewBag.HasLocalPassword)
                {
                    @Html.Partial("_ChangePasswordPartial")
                }
                else
                {
                    @Html.Partial("_SetPasswordPartial")
                }
            </div>
        </div>
    </div>
</div>


@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

Next Steps

All that’s left now is to get our list of user-specific notifications into our view. Tomorrow we’ll get a view model figured out, populate it with the user’s notifications and get it rendering in a Bootstrap-styled table in the view.

Day 25: Personalizing Notifications

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.

Back on Day 19 we introduced persistent storage for notifications, allowing us to pop a custom badge up in the navbar. This was great, but as we left it, it was creating notifications only in the seed method of our DbContext migrations configuration, and the notifications were shown to all users. Not too helpful for dialing in on specific details or messages for specific users.

Today we’re going to get that “everyone’s data” out of the mix, update our notifications so that they belong to a single user and then create a temporary way for us to add new, user-specific notifications to the site.

Clearing our DB and Seed Method

Let’s get those records (from our seed method) out of the database. Locate your DB in SQL Server Management Studio and delete the rows. Something this simple is adequate:

delete from notifications

Now, the only thing is that effort is all in vain if we don’t clean out our seed method. Each time the database configuration class is used to perform or check for migrations it will re-insert those rows.

Locate the Configuration class, which should be in \Migrations directory in the root of your solution. Comment out or delete all the code we added to upsert the notifications.

Extend our Notifications Class

Let’s next add a couple of properties to our Notification class, located in \Models.

public string UserId { get; set; }
public bool IsDismissed { get; set; }

Remember that when we modify a class that takes part in our Entity Framework works that we’ll also need to generate a migration and update the database to match our model. Type these commands into the Package Manager Console, updating the namespace appropriately:

Add-Migration PersonalNotifications -ConfigurationTypeName SimpleSite.Migrations.Configuration
Update-Database -ConfigurationTypeName SimpleSite.Migrations.Identity.Configuration

The first command creates a migration for us, and the second updates the database accordingly.

Updating our ActionFilter

So, if notifications belong only to users, we never want our filter to execute if the current request is for an unauthenticated user. We’ll also want to make sure that we only capture notifications for the user that is logged in, and then, only the notifications that have not yet been seen. 

Here’s the updated code for the NotificationFilter (located in \Filters):

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
    if (!filterContext.HttpContext.User.Identity.IsAuthenticated) return;

    var userId = filterContext.HttpContext.User.Identity.GetUserId();

    var context = new SiteDataContext();
    var notifications = context.Notifications
        .Where(n => n.UserId == userId)
        .Where(n => !n.IsDismissed)
        .GroupBy(n => n.NotificationType)
        .Select(g => new NotificationViewModel
        {
            Count = g.Count(),
            NotificationType = g.Key.ToString(),
            BadgeClass = NotificationType.Email == g.Key
                ? "success"
                : "info"
        });

    filterContext.Controller.ViewBag.Notifications = notifications;
}

Scaffolding a Temporary Controller and View

The MVC Framework has some great scaffolding capabilities, as we’ve explored in minor detail so far. Today we’re going to use this feature to create our whole controller and the related views for all our CRUD operations. Right-click as you normally do on the controllers folder, and click Add->Controller.

This time ‘round, use the Scaffold for the “MVC5 Controller with views, using Entity Framework”. Fill out the options as follows:

image

You are selecting the Notification model, checking off “Generate views” and “Use a layout page”. The controller name should automatically be set to NotificationsController for you. Click Add to finish it out.

image

One more thing: you’re going to want an easy way to get your UserId – it’s what we’re using to match the notifications – so add the following to your Create view in Views\Notifications\Create.cshtml:

@if (User.Identity.IsAuthenticated)
{
    <p>Your User ID is <b>@User.Identity.GetUserId()</b></p>
}

That will output your UserId (which is a Guid) so that you can create notifications for yourself.

Now when you run the site, sign in and navigate to the /Notifications path. This will show you an empty list, but you’ll have a link to create some new records. Add some to the site, using your UserId, and watch the navbar light up.

image

Next Steps

Now, I did say this is a temporary solution. By no means would you actually have a situation where you’d have users enter their own notifications, you’d more likely have events happen in the system that require some notification to be required – perhaps the completion of a job or a required update to some business process.  That’s why we just used the scaffolding today…the NotificationsController and view are something that you’ll likely eventually just delete…and that’s okay! One of the nice things about scaffolding is that you’re not married to it. So delete it when you’re done with it.

In the real world, however, you would likely want users to be able to see and manage notifications in some way. Tomorrow we’ll look at getting the first of those bits in place.

Day 24: Storing User Profile Information

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.

Session is an attractive and oft-used mechanism for storing user profile data. It’s freely available and has been around forever. But session state and logged-in user identity, while they may seem closely related, do not operate on the same lifecycle and sensitive data, personal data, could get “leaked out”.

And hey…this post assumes you’ve been following along with the series and you have already signed in at least once with a registered user.

A Better Place to Store User Profile Data

In yesterday’s article we penned in the user’s choice of Bootstrap Theme and stored their selection in the Session object. Brock Allen wrote a great post a couple years back on why this kind of thing isn’t a great approach. The things that concern us most are that:

  • By default, session isn’t durable and doesn’t scale
  • Even if we move to a more durable session management approach, there’s no persistence of session data and yet we’re making network hops
  • Session isn’t tied to users signing in or out

So, today, we’re going to fix that Session access with a permanent, more reliable and secure approach.

Extending the User Profile Data

Since you’ve already created an account, you technically have some profile information already stored in your site’s database. We’re going to leverage the identity infrastructure of our project and extend the class that keeps track of our data, adding in the user’s selected theme. In your Solution Explorer, locate the ApplicationUser class under Models. The easiest way is usually just through the search box at the top:

image

Add the following property to your ApplicationUser class:

public string CssTheme { get; set; }

Something to keep in mind: we’re going to be modifying a class that participates in Entity Framework persistence, as managed by the Asp.Net Identity libraries. This is handy, but not free. Because we’re changing essentially the schema of a table, we’ll also need to enable and create a migration from the Package Manager Console:

Enable-Migrations -ContextTypeName SimpleSite.Models.ApplicationDbContext -MigrationsDirectory Migrations\Identity
Add-Migration CssTheme -ConfigurationTypeName SimpleSite.Migrations.Identity.Configuration

Note that we’ve got a pre-existing migration on our site, so we need to now be more specific and explicitly name the Configuration type. Also, in enabling the migrations, I added the MigrationsDirectory folder for the DbContext, so that our identity-related migrations would be in a sub-folder.

The Entity Framework created the appropriate classes for me to track DbContext-specific settings and the migration that I needed to update the database, but those are just the classes, nothing’s changed in the DB yet. That all needs to be followed by an update to our database like so:

Update-Database -ConfigurationTypeName SimpleSite.Migrations.Identity.Configuration

We can now store the data we need to, we just need a way to be able to stuff it in there.

Updating our Controller

Since we’re now targeting a user managed from the Identity libraries we’re going to wipe out the code that writes to session and instead use the relevant classes to locate the user profile and update it. Head over to ProfileController.cs (in Helpers\) and replace the call to Session with the following:

var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext());
var manager = new UserManager<ApplicationUser>(userStore);
var user = manager.FindById(User.Identity.GetUserId());
user.CssTheme = themename;
manager.Update(user);

We resolve the user through a UserManager, and the manager needs a UserStore to locate it’s data. We can then set the CssTheme and update the user through the manager. ApplicationUser and ApplicationDbContext are just the names of the types that were automatically created for you through the project template.

It’s only 5 lines of code to access and update a property, but you can see how there must be a better solution to all this than having to write this code all the time. Some day I bet a post will pop up on that…

Updating our Layout

Open up _Layout.cshtml (in Shared\Views) and update the code that resolves the correct style bundle. We’re going to use a similar approach to what we did in the controller to find the user and property, and we’ll handle the null case a little differently than we were previously as well by setting the default in advance.

@{
    var theme = Bootstrap.Theme.Stock;
    if (User.Identity.IsAuthenticated)
    {
        var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext());
        var manager = new UserManager<ApplicationUser>(userStore);
        var user = manager.FindById(User.Identity.GetUserId());
        theme = user.CssTheme ?? theme;
    }
    @Styles.Render(Bootstrap.Bundle(theme))
}

Our other line of code – to actually render the bundle – will remain the same, as you can see at the bottom.

Wait, What Did We Actually Do Again?

I know, I know, it’s hard to put time into something when it seems that nothing really changed. Our functionality is identical and users still have the same options as they did before.

image

But technically our solution is a little more sound.  Here’s what we did again as a bit of a recap:

  • We added a CssTheme property to our ApplicationUser class
  • We enabled migrations on our ApplicationDbContext, using a specify folder for our identity migrations
  • We added a migration to accommodate our new CssTheme property
  • We updated our controller to use the Identity objects instead of session
  • We refactored our _Layout to get the theme of choice from the user’s profile information

Next Steps

For brownie points here, one could likely go to the “manage” bits (under Controllers\AccountController and Views\Account) and allow the user to make a theme selection from there. It’s likely a better home than continuously being available from the home page.

Hang on a sec, though…if we’ve got a place to store information about specific users now, why don’t we revisit our code that puts up those lovely notification icons in the navbar?

Day 23: Choosing Your Own Look-And-Feel

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.

Here’s the thing: everybody’s site is going to look the same if everybody’s site uses Bootstrap, right? Well, if we did that to users, we’d sure be missing the point as developers, and for two key reasons: 1) With the LESS and SASS source it’s easy to customize, and 2) Because it’s easy to customize, there’s already people creating all kinds of alternate themes for Bootstrap.

So, we aren’t headed down a slippery slope here, we just need to make a little effort to give our users some unique looking sites.  Other posts will show you how to replace the Bootstrap theme, but this one will show you how to let your users choose from a list you’ve pre-built.

Download a Free Substitute

There are some great, free alternatives located at Bootswatch.com. So, start there and pick one or two to download, I chose Amelia and Darkly. We need to create a folder structure to organize our themes, and move the CSS into those folders. Mine ended up working like this:

image

Note that I also pushed a copy of the stock CSS for bootstrap into this structure. This allows us to simplify our code for theme switching, allowing users to pick the base theme if they like.

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.

Creating a Helper Class

Next, we create a class called Bootstrap.cs (I put mine in \Helpers) so that we can programmatically work with the themes. This class is responsible for presenting the list of supported themes and resolving the path to them when we try to load the bundles.

public class Bootstrap
{
    public const string BundleBase = "~/Content/css/";

    public class Theme
    {
        public const string Stock = "Stock";
        public const string Amelia = "Amelia";
        public const string Darkly = "Darkly";
    }

    public static HashSet<string> Themes = new HashSet<string>
    {
        Theme.Stock,
        Theme.Amelia,
        Theme.Darkly
    };

    public static string Bundle(string themename)
    {
        return BundleBase + themename;
    }
}

This is a simple class, but it prevents us from duplicating code all over the place or unnecessary spelling mistakes.

The other nice thing is that if you choose to add another theme to your project, you will just have to modify this one file and the rest will fall into place.  For that to happen, we’ll need to modify our startup to generate all the appropriate bundles.

Updating Our Startup Bits

Head into BundleConfig.cs (inside of \App_Startup) and replace the code that creates the Bootstrap bundle with the following:

foreach (var theme in Bootstrap.Themes)
{
    var stylePath = string.Format("~/Content/Themes/{0}/bootstrap.css", theme);

    bundles.Add(new StyleBundle(Bootstrap.Bundle(theme)).Include(
                stylePath,
                "~/Content/bootstrap.custom.css",
                "~/Content/site.css"));
}

We’re simply looping over that handle collection we created so that we could generate a bundle for every installed theme.  We always want all the themes – startup is only run at as the application starts, so we need them all there – as different users may wish to select different themes.

Making Our Layout “Themeable”

What we really need to do here is just a quick update to figure out the user’s current theme, and then figure out what the correct bundle to use is.

@{
    var theme = Session["CssTheme"] as string ?? Bootstrap.Theme.Stock;
}
@Styles.Render(Bootstrap.Bundle(theme))

I’m using Session for now, but I’ll explain why in a bit that is bad idea. Smile

Note that, at this point, you could set that theme default – right now set to Bootstrap.Theme.Stock – to whichever theme you like and run your app. The mechanics of building the bundle and the class to resolve it are all in place.

Letting the User Choose a Theme

Once again we’re going to revisit the _LoginPartial.cshtml file (in Views\Shared). In this round, we’re going to update the text that shows the logged in user’s email address (which, by default, is also their username). The LI for the username is now going to be a dropdown box in the navbar.

<li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Hello @username! <span class="caret"></span></a>
    <ul class="dropdown-menu" role="menu">
        <li>
            @Html.ActionLink("Manage Account", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
        </li>
        <li class="divider"></li>
        @foreach (var theme in Bootstrap.Themes)
        {
            <li><a href="@Url.Action("ChangeTheme", "Profile", new { themename = theme})">@theme</a></li>
        }
    </ul>
</li>

I’ve taken that LI that was there – all it had was the user name, which was a link to Manage Account – and replaced it will all of the above code. We put in a divider and iterate over the list of known themes.  Each will be a link to a “ChangeTheme” action on the “Profile” controller.

Adding our New Profile Controller

Throw ProfileController.cs in your \Controllers directory with the following, lone action in the class:

public ActionResult ChangeTheme(string themename)
{
    Session["CssTheme"] = themename;
    if (Request.UrlReferrer != null)
    {
        var returnUrl = Request.UrlReferrer.ToString();
        return new RedirectResult(returnUrl);
    }
    return RedirectToAction("Index", "Home");
}

If we have a referring URL we can push the user back to the same page, otherwise we ship them home. The preference of theme is set in the Session.

And there you have it: users can now pick their own theme on your site:

image

Next Steps

This data doesn’t really belong in the user’s session…whenever the app pool is recycled or the website or IIS is restarted or their session expires they will lose this choice. Even worse, session and Identity aren’t on the same lifecycle, so when they log out the session persists and they’ll still see the theme they chose when they logged in.

So, where should it be stored? Tune in next time as we answer this question and more. Smile with tongue out

Happy coding! Smile

Day 22: Sprucing up Identity for Logged In Users

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.

Typically you wouldn’t want the entirety of the internet adding and editing records at will without some form of authentication and authorization so that you can keep track of who’s editing your data, or so that your users can keep track of their own.

So, let’s continue with our project and build out some identity capabilities.

Okay, I’m Kidding. Just Press F5!

Great work, you’re all done!

As most folks are well aware, the default templates for Asp.Net applications now ship with a sample account administration implementation (reasonably good ones, at that). Users are able to register and log in using pre-built models, controllers and views. You can easily extend the template with 3rd party login capabilities, allowing folks with Microsoft, Facebook or Google accounts (and, and, and…) to log into your site as well. We’ve now got substantial improvements to identity management overall, with things like two-factor authentication, reductions in the leaky abstractions we’ve lived with, better testability, more flexibility in storage options, and more.

If you’re not familiar with these bits, it’s worth having a look, but this is a topic already well covered. Believe me, these are worth the reads:

But we’re here to do Bootstrappy things, right? So let’s spruce up that top bar a little for our logged in users with some MVC bits we build (HTML helpers) and some Bootstrap bits (image classes) that will take our site up a level.

Bootstrap Image Classes

The CSS library gives us a few easy-to-use helpers to make our images look consistent. Here’s a sample from the Bootstrap site:

image

The classes are as follows:

  • img-rounded – provides rounded corners to your rectangular images
  • img-circle – turns any image into a circle
  • img-thumbnail – makes your image look like a little Polaroid of itself

Making Members Feel Welcome

Today we’re just going to add a little touch to the navbar that our logged in users will see, keying in off of the default implementation of the Identity providers.  We’ll head in that direction by extending our HtmlHelper that generates Gravatar images, as we need to add a property for a CSS class to give us a nice round face on the page.  But first, we’ll have to add the following line of code to the GravatarOptions class:

public string CssClass { get; set; }

We’ll need to add that to the tag, so let’s revist the GravatarImage, likely located in the Helpers folder, to check for a value and add it to the tag if present. The full method should now look like this:

public static HtmlString GravatarImage(this HtmlHelper htmlHelper, string emailAddress, GravatarOptions options = null)
{
    if (options == null)
        options = GravatarOptions.GetDefaults();

    var imgTag = new TagBuilder("img");

    emailAddress = string.IsNullOrEmpty(emailAddress) ? string.Empty : emailAddress.Trim().ToLower();

    // <-- adding support for CSS
    if (!string.IsNullOrEmpty(options.CssClass))
    {
        imgTag.AddCssClass(options.CssClass);
    }
    // adding support for CSS  -->

    imgTag.Attributes.Add("src",
        string.Format("http://www.gravatar.com/avatar/{0}?s={1}{2}{3}",
            GetMd5Hash(emailAddress),
            options.Size,
            "&d=" + options.DefaultImageType,
            "&r=" + options.RatingLevel
            )
        );

    return new HtmlString(imgTag.ToString(TagRenderMode.SelfClosing));
}

Unfortunately there isn’t quite the exact Bootstrap class we need to make our image place and size well in the navbar, so we’ll need to open up our bootstrap.custom.css file and add the following structural class:

.navbar-image {
  float: left;
  padding: 10px 5px;
}

Finally, we’ll pop over to our _LoginPartial.cshtml (in Views\Shared) and modify the block of code displayed for logged in users.  Because I’m reusing the user’s name a couple of times (which is also their email address) I’m storing it in a variable first, and using that throughout the block. I also add a DIV as a container for our image, using the class that we just created. Last, I make a call to our GravatarImage helper, passing in the username (email!), an appropriate size for the toolbar (30px), and the Bootstrap class that gives us the shape we’re looking for (img-circle).

var username = User.Identity.GetUserName();
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
        
@Html.AntiForgeryToken()
    
<div class="navbar-image">
    @Html.GravatarImage(username, new GravatarOptions { Size = 30, CssClass = "img-circle" })
</div>
    
<ul class="nav navbar-nav navbar-right">
    <li>
        @Html.ActionLink("Hello " + username + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
    </li>
    <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
}

And now we’re rockin’ head shots in our navbar!

image

Next Steps

Perhaps you’ve modified your user profiles so that the username doesn’t have to be an email address. You could easily modify this example to read from a different property and generate the same type of effect.

What is sparkle without shine? Let’s give our users the ability to choose their own look-and-feel.  I mean, it worked for GeoCities, right?

Day 21: Cleaning Up Filtering, the Layout & the Menu

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.

In software development we often talk about concepts like the Single Responsibility Principle. Web pages are often doing lots of things, so it’s hard to say that it should always apply when we’re building our views. But, in the spirit of Martin Fowler’s take on it, I would argue that our _Layout.cshtml is starting to get a lot of reasons as to why it might change, and for that reason, we’re going to split out the menu.

Extracting the Menu

In your Views\Shared folder add another partial called _MenuPartial.cshtml and paste in the following code.

@using SimpleSite.Models
<ul class="nav navbar-nav">
    <li>@Html.ActionLink("Home", "Index", "Home")</li>
    <li>@Html.ActionLink("About", "About", "Home")</li>
    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
    <li>@Html.ActionLink("My Peeps", "Index", "Simple")</li>

    @if (ViewBag.Notifications != null)
    {
        foreach (NotificationViewModel notification in ViewBag.Notifications)
        {
            <li>
                <a href="#">
                    @notification.NotificationType
                    <span class="badge badge-@notification.BadgeClass">
                        @notification.Count
                    </span>
                </a>
            </li>
        }
    }
</ul>

If you flip back to our _Layout view, you’ll see that this is very close to what we had there. I’ve made two important changes:

  1. I’ve added a link to our SimpleController in the menu.
  2. I’m checking to make sure there is data in the ViewBag before accessing the dynamic property. This will prevent errors should there be no notifications for the users.

If you do #1 without #2 above, you will most definitely get errors because the only place that has notifications injected is in the Index action on the Home controller.

With those bits in place, be sure to pop back into your _Layout, and update the navbar where we had previously added the code for notifications. It should now only include a call to render our _MenuPartial and the _LoginPartial.

<div class="navbar-collapse collapse">
    @Html.Partial("_MenuPartial")
    @Html.Partial("_LoginPartial")
</div>

If you run the site at this point you won’t get any errors, but you’ll only see the notifications on the home page. Let’s address that.

Globally Registering an Action Filter

We’re now going to set it up so that our NotificationFilter is executed on every request. I just ask that you remember that this is a demo, and that there are a few caveats you should be aware of.

During application startup (checkout your global.asax in the root of the site) you’ll notice a call to FilterConfig.RegisterGlobalFilters. There is no magic here. There’s a static method on a class located in your App_Start folder that helps to keep that global.asax nice and tidy. A GlobalFilterCollection is passed in and we can then add to it.

In previous versions of the MVC template, this wasn’t around, so most folks ended up either dropping in a ton of lifting into Application_Start or otherwise coming up with a comparable solution to the above. Now, the class that does the FilterConfig does the FilterConfig. Kinda like that whole Single Responsibility Principle again, eh?

Update FilterConfig (which has the global error handling baked in already) to also include the registration of our filter:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new NotificationFilter());
}

Now, return to the Home Controller and remove the NotificationFilter attribute from the Index action.  It won’t really matter if you don’t (the Framework is smart enough to see that it’s already in play) but you might confuse the future version of yourself when you disable the global registration down the road and the filter keeps getting executed.

You’re all set!

Next Steps

One final step that you might want to consider in the clean up is to move your notification model to a separate DLL, but I’ll leave that as an exercise to the reader as it’s more of a “code” thing and less of an “MVC or Bootstrap” thing.

Next up, we’ll tackle user registration and membership.