JavaScript Views for Easier Ajax (with JQuery)
May 15th
I tweeted Phil Haack a while ago asking for a new feature in Asp.Net MVC 3. That feature was JavaScript views. What the heck is a JavaScript View? Well first, let’s define what the problem is and then you will see how JavaScript views can be very helpful. Let’s look at how we make an ajax request in JQuery
$.ajax({
url: "test.html",
cache: false,
success: function(html){
$("#results").append(html);
}
});
Do you see a problem? You might not, because this is a valid statement. The problem is with the url property. It is hard coded to be “test.html” which might be ok for simple applications, but this can be problematic as your application gets larger.
Asp.Net 4 (or 3.5) to the Rescue
If you’ve been keeping up with Asp.Net then you know there is something new called routing. It allows you to define friendly urls. It is integral to Asp.Net MVC. From this point on, I will assume you know about Asp.Net MVC and routing. I have a complex site that has actions, several of which are purely for Ajax. The issue is that my routing scheme is still very experimental and I am still deciding on how to get the prettiest urls I can. What is very solid is the functionality each of these actions perform. So what is the challenge.
How do I dynamically inject urls into JavaScript by utilizing the Routes I have already defined?
Luckily the solution is very straightforward and easy to implement. Let’s look at how your JavaScript file might look like.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
$(document).ready(function() {
$(".button").click(function() {
$.ajax({
type: "POST",
url: "<%= Url.Action("Ajax","Home") %>",
success: function(response){
$(".result").html(response.message);
}
});
});
});
Sweet right! Well it isn’t that easy. You have to set somethings up in your MVC project before this works.
Step 1 – Create a Controller
Create a controller specifically for handling dynamic JavaScript views.
public class JsController : Controller {
public ViewResult Index(string file) {
return View(file);
}
}
Step 1 is complete. We need a controller so that a RequestContext is passed to our JavaScriptView, without this our views will bomb. Let’s move on to Step 2.
Step 2 – Specify the Route
routes.MapRoute(
"JavascriptViews",
"js/{file}.js",
new { controller = "Js", action = "Index", file = UrlParameter.Optional });
We need this route, so that MVC handles requests and points them to our controller.
Step 3 – Create Your JavaScript View and Link it

Add a new view under a “Js” folder under the “Views” folder. That’s it! All you need now. You can start utilizing the tools inside of Asp.Net MVC to start generating routes. Technically, you could do a lot more than just generate routes, but I wouldn’t go crazy with using C# to generate your JavaScript files.
<script src="js/master.js" type="text/javascript"> </script>
Conclusion
This is a great way to manage the Urls in your JavaScript files without the concern of worrying about modifying all your JavaScript files just because you want a different route. Download my sample and see if you like it or you think I’ve gone completely insane.
Using the 960 Grid System for Layout
May 5th
So I’ve been using the 960 grid system for over 6 months now and I have learned a thing or two that could be helpful to those looking at using it as well. If you don’t already know, 960.gs is a css framework to help you quickly enable layouts and help ease the pain of cross browser compatibility. I will start by laying out the pros and the cons of the 960 and then show you how to overcome possible gotchas.
The Pros
This is what you want to hear right, how is 960.gs going to make your layout easier to manage and create. Well let’s start then.
- Complex layouts relatively fast.
- Consistent layout (IE, Firefox, Chrome, …)
- Reusable and Flexible
- Easy to learn
The Cons
Ok so some of the down sides of using 960.gs, cause there are some obvious ones.
- More stylesheets ( 960.gs, reset.css, text.css and then yours)
- Respect it or it will bite back
- Divitus (lots of div tags based on your layout)
- Everything you need to do isn’t a grid
- not semantic (grid_12 is not expressive)
- multiple css classes on one element
Overview
by default the 960.gs is split into either a 12 column grid or a 16 column grid. I will focus on the 12 column grid. Each column in a 12 column grid is 60px wide with a margin of 10px on each side. You can see that below the max content area you can have is 940px, while the container expands to 960px due to the 10px margin on each side. You can also see that the margin between two columns is 20px, because each column has a 10px when two columns margins combine they make 20px. And finally, a div tag can span multiple columns and it’s length is made up of all the columns it spans and 10px of margin on each side.
ex. a column that spans 11 columns is 880px. column: 60px + 10px + 10px. 11 x 80px = 880px total : 880px with outside margins and 860px without outside margin (content area).
Ok that was a lot of math, but you only need to know how to count up to 12 or 16 to use this system. No need to do this math because it is done for you automatically. The point of the math is to show you that the box model is important to understand. Margin is outside of your div tag, while everything else is inside.
Example – The Basics
So you are curious about the above example, how what does the HTML look like? It looks like this.
<div class="container_12"> <h2> 12 Column Grid </h2> <div class="grid_12"> <p> 940 </p> </div> <!-- end .grid_12 --> <div class="clear"></div> <div class="grid_1"> <p> 60 </p> </div> <!-- end .grid_1 --> <div class="grid_11"> <p> 860 </p> </div> <!-- end .grid_11 --> </div>
Simple right, you see that we use a div with a class of container_12. This is used to help center your page and give a place to start laying out your page. The next thing you will see is grid_12. That is telling that div to span the whole way across, and it is then followed by grid_1, and grid_11. You can guess that we are specifying that the first div is a size of one column, while the next is 11 columns. The div with a class of clear forces the grids to the next line, but I have found if your rows always add up to 12 you can forgo the clearing, since floating will force elements to the next line anyways, that is up to you.
Gotchas
The first and major gotcha that people run into is they attempt to overly style their div tag that already has a grid class. This is a mistake and can lead to huge headaches. Let’s look at why you shouldn’t. I will show you what css rules are ok to use and which aren’t.
Border
The first no-no is border. You shouldn’t use border on your grid divs because it adds size to your layout.
ex. You have a grid div that spans 5 columns. 5 x 80px = 400px. So you want to add a border of 1px solid black (always bet on black). What does that do?
That changes the math 5 x 80px + 2px (border-left and border-right) = 402px. now 2px might not seem like a lot, but it can force whole divs to the next line, throwing off your layout completely.
To fix this problem you should put another div inside the grid div and then style that. What you end up with is a container –> content relationship.
Margin and Padding
So you want to move a grid just a little bit over huh? DON’T. The same problem happens that occurs with Border. You force the columns to stretch pass what they were designed to do. Think of yourself trying to wear pants that are two sizes too small, it just isn’t pretty.
The solution again is to use a container-> content relationship. Where you have another div inside that handles margin and padding.
Width
You might be seeing a theme here, width is the enemy of the grid system, especially explicit widths. If you have an element that is 200px in a column that is only 60px, then you’ll have problems.
The solution is to be mindful of your parent div. If you want to use width, look at using percentage. ex. width: 100% on the content div.
Things that are OK to Style:
background-color, color, background-image, position (absolute and relative).
Conclusion
The 960.gs is very powerful, but some CSS purist might not like it’s lack of semanticness (not sure if that’s a word). I see their point, but the up side is so great that I can overlook my HTML/CSS purism. Keep in mind the gotchas and you should be able to create consistent layouts in all major browsers.
FluentSitemap: Build Sitemaps for Asp.Net MVC
Mar 24th
Building your site is only half the battle. Getting people to know it exists is the other half. If you are creating a public facing site, or even an intranet that utilizes an in-house search server then I have created a library just for you. The library is FluentSitemap. This library is designed to help you easily build sitemaps to be utilized by major search engines. The great thing about this library is that utilizes all your existing routes and controllers to build a sitemap even for the most complex Asp.Net MVC sites.
The FluentSitemap library can be found at GitHub Here.
How to use you, Let me count the ways
There are several ways you can utilize this library. The first is to specify each node manually. Let’s look at how that looks.
// You can pass in a HttpContext from anywhere
// in you application
ISitemapConfigurator configurator = new SitemapConfigurator(HttpContext);
// create sitemap node and set
ISitemap sitemap = configurator.Create()
.WithLocation("http://localhost.com/")
.WithPriority(0.3)
.WithChangeFrequency(ChangeFrequencyType.Never)
.Set().Export();
The second is to use a controller/action pair.
// You can pass in a HttpContext from anywhere
// in you application
ISitemapConfigurator configurator = new SitemapConfigurator(HttpContext);
// Add From a controller and action
ISitemap sitemap = configurator.Add("Home", "Index")
.Add("Home", "About").Export();
The third is to use a route
// You can pass in a HttpContext from anywhere
// in you application
ISitemapConfigurator configurator = new SitemapConfigurator(HttpContext);
// Add From a controller and action
ISitemap sitemap = configurator
// Add From a Route
.AddFromRoute("Default", new {id = "2"}).Export();
The last is to use the ISitemetadata. This is specifically there for IoC.
public class HomeControllerSitemapMetadata : ISitemapMetadata
{
private const string Home = "Home";
#region ISitemapMetadata Members
public void Create(ISitemapConfigurator sitemap)
{
sitemap.Add(Home, "Index")
.Add(Home, "Scanner")
.Add(c => c.Metadata());
}
#endregion
}
public class OtherControllerSitemapMetadata : ISitemapMetadata
{
private const string Other = "Other";
#region ISitemapMetadata Members
public void Create(ISitemapConfigurator sitemap)
{
sitemap.Add(Other, "Index")
.Add(c => c.Test(1, "dude"));
}
#endregion
}
// An example, you'll probably use your favorite
// IoC container to resolve all the metadata classes
var metadata = new List
{new HomeControllerSitemapMetadata(), new OtherControllerSitemapMetadata()};
ISitemap sitemap = new SitemapConfigurator(HttpContext).FromMetaData(metadata).Export();
There is more API sugar, so go download it and give it a try.
MVC Turbine – A Great Platform
Mar 22nd
I love Asp.Net MVC, that isn’t a secret. Although the framework isn’t perfect, it is a great leap in the right direction. When I start an Asp.Net MVC project there are things I always have to do just to jump into the meat of the new site. These things include replacing the ControllerFactory with a IoC enabled ControllerFactory, changing routing, and other boiler plate actions. This is where MVC Turbine comes in, and I am liking it more and more the deeper I dive into it. Javier Lozano, the creator, defines MVC Turbine as
MVC Turbine is a plugin for ASP.NET MVC that has IoC baked in and auto-wires controllers, binders, view engines, http modules, etc. that reside within your application. Thus you worry more about what your application should do, rather than how it should do it.
If you consider ASP.NET MVC as a stock Nissan 370z, then MVC Turbine is the Nissan 370z with the Nismo package. Ultimately the same car, but the tweaks make the ride so much more fun to drive. Everyday I find something cool in this framework, but these are my favorite features so far.
Services Registration and IoC
I love IoC, because it makes testing your applications easier and shrinks your code base over the long run. What I hate is having to wire it up every time I start a new project. With MVC Turbine, it is already handled for you. Just create classes that implement the IServiceRegistration interface. You will be passed your favorite IoC and you can do what you need to do to register your services.
Inferred Actions
If your controller actions just return a view, then you are going to love this. You can create a controller class with no actions, and MVC Turbine will look in your views folder and display that view. Check it out here.
Route Registration
When you have a large Asp.Net MVC application, then you’ll probably have a lot of routes. MVC Turbine allows a great facility for registering routes, while keeping you project clean.
I can definitely get behind MVC Turbine and I recommend you check it out.
ASP.NET MVC 2 RTM, Content Management System, & ValidateInput
Mar 15th
I have a lot of clients asking whether I can enable them to edit their own content. Most of the time I ask questions that make them realize that they don’t really need it, but sometimes they really do want it. I’ve been developing ASP.NET MVC web applications in VS2008, but as VS2010 comes closer to being released and with ASP.NET MVC 2 hitting release, I am starting to focus my efforts on using both technologies. So I sat down today and looked at CKEditor, a WYSIWYG editor that is embeddable into your site.
The issue that I found is that ASP.NET 4.0 is really concerned about Security, so much so that it ignores my ValidateInputAttribute on my controllers. When I submit my HTML content from the client, the MVC application throws a red screen of death. By default, ASP.NET will validate all incoming requests to make sure there are no malicious things coming in. The ValidateInputAttribute was designed to tell ASP.NET that this request is meant to contain things that might be dangerous.
There is a really simple fix to this, and it is one line long.
Solution:
- Open up your web.config
- Under System.Web add a httpRuntime node.
- Add requestValidationMode attribute and set it to “2.0”
The solution defaults back to ASP.NET 2.0’s request validation, which will respect your ValidateInputAttribute on your controller actions.
Hope this helps.
-Khalid Abuhakmeh
C4MVC Presentation on Database Migrations
Mar 15th
Hello everybody. It has been about a week since I gave my C4MVC presentation on database migrations. The video is below, and the code is also downloadable below.
Asp.Net MVC 2 Quick and Simple Site – v1
Mar 9th
*Note: Asp.Net MVC 2 project in Visual Studio 2010
I sat down last night and was thinking about how I could get a simple starter site up and running for a client, until I could design something more tailored to their needs. There is nothing worse than having a “under construction” page or a “coming soon” page. It doesn’t really say much about what is happening or what might be coming. So I sat down and came up with the basics of what a client might want right from the start, here were my requirements.
- Set a Logo, Name, and Subtitle
- Be able to quickly edit a small about section (Content)
- Quickly add some of the more important social networks (Twitter, YouTube, FeedBurner, Delicious, MySpace, and Facebook).
- Be able to add Google Analytics (Optional)
- A dynamic image gallery (drop images in a directory and everything is done for you).
- Basic contact information. Email, Phone, and Website.
- No external libraries to install (this hurts but is helpful).
So I sat down and started writing. I wanted someone to be able to push this site without editing a lot of files or having to setup a database. I opted to put a lot of the client’s settings in configuration. Yes configuration sections are not the new hotness but they can still serve a powerful purpose.
My first iteration had me using controller actions for each part of the site, but I slowly realized it was overkill. I opted to have one controller action from my index, and then break sections up into partial views that would be all rendered at the same time. Then those sections would be hidden and made visible using JQuery. After a little design, I ended up with this.
Let’s look at how to set this up.
Step 1 – Setup the Configuration
There are some pretty simple configuration sections in the web.config included with this project. You will see two App settings: WorkImagesDirectory and GoogleAnalyticsCode. The WorkImagesDirectory is used to find all the images in your gallery. Thumbnails for all your images will be automatically created if they are missing. The GoogleAnalyticsCode setting should be set to your Google Analytics code UA-XX-XXXX (or something like that). If you leave out the Google Analytics code then the script won’t be output to the page.
Next you will see a ContactInformation section. In this section you can set the name, site subtitle, email, phone, and website.
Finally, you will see a SocialNetworks section. Only the social network usernames you set will show up on the page. You can set Twitter, Facebook, YouTube, Delicious, MySpace, and FeedBurner(a blog maybe).
Step 2 – Setup Content
Once the configuration is done, then you probably want to change some of the content to reflect some good information.
All tabs are separated into partial views: About, Contact, Work, Social. Just replace the HTML content in here with what you want, leaving the nested RenderPartials.
Step 3 – Modify Colors and Images
All the images and style sheets you need to modify are under the Content directory. If you like the color and just want to modify the avatar at the top, just overwrite the avatar.png under Content/img.
Step 4 – Deploy It
Just publish what is there to your hosting provider and you are ready to go.
Conclusion
This is a good little site to get up and running for your clients, but it isn’t anything ground breaking. The code is straight forward, so even a novice can get in there and change things. The point here was not to over complicate the solution with third party libraries. It is to get a site up with in minutes, while still giving some great functionality to the people that need it.
Git –newbie –workflow
Mar 3rd
Introduction
I recently found the time to dedicate to learning a distributed version control system. I had the choice between Mercurial and Git. Both are great systems but what it came down to ultimately was the fact that I already had TortoiseGit on my machine. Yes you read that right, it came down to the fact that I didn’t want another source control provider taking up space in my context menu; frankly my context menu is getting a little ridiculous.
I know it isn’t exactly a scientific method of picking between the two, but honestly, I see very little that is different between the two (for a learner).
Initial Reaction
When I first read the description of Git, I thought “who would be stupid enough to have source control on their own machine?” The second thought to go through my SVN-centric brain “I like SVN, so why should I change to Git?” The first question came out of ignorance to the ideas behind a distributed source control system, the second is a completely valid rebuttal.
I will attempt to address the first question. Yes your source control is on your machine but think of it as your own personal local copy of the “Truth.” You edit your version of the “Truth” until you feel comfortable with your additions and changes. The next step is to push your changes to a central version, possibly on GitHub or Unfuddle. That last step is important, because your source is no longer local. Your code now exists somewhere that is hopefully safe, secure, and accessible to you and your team of developers. What is powerful about Git is the fact that most of the expensive actions performed locally: commits, merges, additions, and deletions. This makes Git crazy fast, CRAAAAZZZY FAST! The two most expensive actions are pull and push, but even these can be quick if your central source control repository is on the local network. After a couple hours playing with Git, my ignorance about the ideas behind this system were overcome by an understanding and comfort.
The second question is valid. If you like SVN, why should you switch? Well nobody is forcing you to switch, and people won’t call you a loser if you decide to stick with SVN. I still have a warm place in my heart for SVN, it was the Han Solo of my escape from the Death Star known as VSS (Visual Source Safe). That being said, Git is a lot easier when it comes to branching and merging. In SVN branching occurs remotely on the SVN repository, which can be slow. In Git, branching happens locally and is even encouraged by most resources that I read. The one thing developers might gripe about Git is the fact that there really isn’t much Visual Studio integration. SVN has a ton of integration tools inside Visual Studio. What I would say about this though, is that the projects I work on have more than enough files outside of my VS Solution to negate the good aspects of integration tools. File types like third party assemblies, documentation, build scripts, and other files all exist outside the scope of my solutions. Now to add them to your SVN repository you are forced to use TortoiseSVN, a tool that exists outside Visual Studio.
I may or may not have convinced you to try Git, but I really feel you should. More and more compelling projects are being hosted on GitHub. How will you get involved and help these projects grow with a knowledge of Git? Also, Codeplex now offers Mercurial support, so don’t be suprised when your favorite projects on Codeplex start moving to a distrubuted SCM.
Basic Workflow
To get started with Git download MsysGit. This will setup an environment ready for Git on your windows machine.
I also recommend TekPub, they have a great series about mastering Git.
To learn about a system you have to use it, and that is what I did with Git. I wouldn’t call myself an expert but I do feel comfortable enough with it now to jump into a Git project. The basic Git workflow is as follows (type: “git help” in a command window):
- init or clone: if you are starting a repository use init, if you are getting use clone.
- branch: create a new branch to start working in or just work in the master branch.
- add: add any or all files involved in your project.
- commit: commit staged files to your local source repository.
- pull: get any changes that have occurred at the central repository.
- merge or rebase: make sure all your changes and branches are reflected in the master if need be.
- patch or push: some repositories online are private so you can produce a patch to send to the owners, if you own the repository the push away.
- Rinse and Repeat until content.
These are the commands you’ll need to know to just get by, but there are many more to become a master. I modified my environment to work with WinMerge for both merging and diffing. Below are the instructions to get that working.
- You will need to modify your git environment. This is done through modifying the .gitconfig file found in your user folder (C:\Users\<yourname>\.gitconfig).
*Note, when you install WinMerge be sure to check the box that installs WinMerge into your system path.
[/diff]
external = “c:/users/khalid abuhakmeh/difftool.sh”
[merge]
tool = winmerge
[mergetool "winmerge"]
cmd = ‘WinMergeU.exe’ \”$MERGED\”
trustExitCode = false
keepBackup = false
- Create a bash script to execute against WinMerge. Create a file called difftool.sh and save it in the same directory. Below are the contents of my file.
#!/bin/sh echo Launching WinMergeU.exe: $1 $2 "C:/Program Files (x86)/WinMerge/WinMergeU.exe" -e -ub "$1" "$2" | cat #!/bin/shecho Launching WinMergeU.exe: $1 $2"C:/Program Files (x86)/WinMerge/WinMergeU.exe" -e -ub "$1" "$2" | cat
Now when you execute the commands "git diff @{1}" (compares against previous version) or "git merge" you will get to use WinMerge to perform those actions. Pretty cool.
Conclusion
So there you have it, my initial interactions with Git and what I have learned so far. There are more things to learn, but I am definitely a convert to Git. Can you Dig Git?
Cu3er .Net HttpModule Updates Your Configuration
Jan 8th
So I’ve been playing around with Cu3er, a great flash component for websites. It gives you the ability to create dynamic looking slideshows with great transition effects. I highly recommend you go over to Cu3er site and check it out. What I don’t like about Cu3er is that you can’t point it at a directory and let it pick up the image files dynamically. So I decided to help the .Net crowd with this little speed bump. I’ve done all the tedious work of mapping Xml to objects (trust me, I dislike doing this).
The main goal was to be able to drop images into a directory and update the configuration. I didn’t want to exclude anybody using Asp.Net, regardless whether you are using WebForms or ASP.NET MVC. So I finally ended up going with an HttpModule. The code executes every time a request is made and checks to see whether the contents of the image folder have been updated. For me it isn’t quite ideal, because I am reading the file system every time a request is made. I attempted to to use FileSystemWatcher but I couldn’t seem to get it firing in an ASP.NET environment.
So what are the advantages to using this HttpModule?
- Minimal editing of Xml. Just setup the main settings node in the config.xml file and it will be preserved.
- Could add great functionality to a CMS or dynamic site.
- Configurable from a configuration section
So What are the disadvantages
- Can only define one type of transition for all images.
- It is an HttpModule that fires every request (not ideal in my mind)
How do you make it work better for you?
- If you are using Asp.Net WebForms, create a HttpHandler that creates the configuration every time the config.xml is requested.
- If you are using Asp.Net MVC, create a controller action that returns a ContentResult containing the config.xml every time it is requested.
This is still an initial start to what I think can be a great helper to an already great flash component. Maybe V2 of Cu3er will have this functionality already built in, so this could be obsolete by then as well. But until then you are welcome to use this library and modify this library. I consider the code I wrote as an Alpha, if that. Realize that there could be bugs. Their is no warranty or guarantee expressed or implied (a little CYA).
To make this solution work you will need to do the following.
- Add a reference to the Cu3er .Net Library or Project to your web project.
- Add the configuration section to your web.config
- define the directory path to watch, and the location of the config.xml
- define the Cu3er module in the HttpModules section
- import the Html and Swf into the page you’d like to use Cu3er.
Check out the example I included with the Cu3er .Net project to see how to accomplish the steps above, and be sure to read the Cu3er documentation (the example is in ASP.NET MVC, but doesn’t really use the features of ASP.NET MVC to accomplish the goal).
Oldie But Goodie : Open Flash Chart – Fixing Open Source
Jan 7th
This is from my old blog “Monster’s Got My .Net.” I didn’t realize that there was link to this on the OpenFlashChart site, so I am reposting it here for anyone that would like to use the code. Hope I didn’t inconvenience anyone.
So if you have ever had to write a report of any kind, you know how much your clients are itching to have some kind of chart on the page, and something with a lot of pizzazz. Well the problem is that those charts usually can cost you a pretty penny. Companies like Telerik and Infragistics offer great products, but for those with a budget (you cheap bast’d) there are great open source alternatives. The problem with open source sometimes is that it usually written to support multiple web technologies and not just ASP.NET. Everybody knows ASP.NET is the best and obviously these open source projects are written with a lapse in judgement, but forgiveness is the best policy because these projects can be awesome (just kidding about the lapse in judgement).
OpenFlashChart.zip (694.51 kb (Visual Studio 2008)
What I found in my search was Open Flash Chart,which is amazing. So I downloaded the project and installed it, and it had a .NET example in there (in chinese) and it worked but I didn’t like how it worked. I then looked on CodePlex and found someone who implemented a cool version of Open Flash Chart, but it didn’t work with the newer Open Flash Chart build. The newer version uses JSON. I decided to take both projects and merge them together to make a better mouse trap.This project was written using some of the new features of C# 3.0, so if you need to run it in 2005 then you might need to modify some of the code.
There are three aspects to this project: the ASP.NET Control, the Charts, and an HttpHandler. If you want to see the details of the infrastructure I suggest you look at the original author’s post, I only take credit for fixing it, but he wrote the ASP.NET infrastructure originally.
If you are intereseted in an Open Flash Chart control you can download the assembly here. I will also try to contact the original author and get the latest version on codeplex.
OpenFlashChart.zip (694.51 kb) Visual Studio 2008
Note: The HttpHandler solution utilizes cache, which works until you try to use it on load balanced machines without distributed cache. You can point the control to data pages as a work around. Play around and see what’s in the code. All credit goes to the original authors, I greatly respect their work and have included credit in the example project.
Update : How Ironic, the download to the fix didn’t work. I think it works now so you can download it.


