Recently I was trying to add a simple message to the top of the screen if the user had been logged out.

This message, should appear only once. If the user navigates away from the page, it shouldn’t show again.

So, it made sense to use TempData

In my controller, I had something like this:

Then, in my view, a simple check:

The issue is here, using ContainsKey doesn’t mark the item for deletion. So on page reload, the TempData dictionary still contains that key, so the message is still displayed.

The solution is to change the ‘if’ statement to

Reading (by accessing the dictionary item by index) marks the item for deletion on the next request.

I’ve recently been looking in to building a directory type application with Asp.Net MVC

One of the requirements would be to have SEO friendly URLs such as:—Surrey

/restaurants being the “Category”

/Camberley—Surrey being the “Location”

So, I created a ‘CategoryController’ like this

But how do I map my routes?

What you can use, is RouteConstraints

Simply map your route as usual, but add an instance of our custom RouteConstraint

With our CategoryRouteConstraint as follows:

Of course, our collection of ‘categories’ would come from some kind of store – a database, cache, etc…

Now, if we run the app and visit /restaurants/Camberley–Surrey, our route resolves as we expect.

Demo: On github

Session_Start event not firing

I’ve been scratching my head about this one for sometime…
As I’m sure your aware (or you wouldn’t be reading this) in the Global.asax file, we have the following method:

Placing a breakpoint on this method, I attached the debugger, ran up my application, and the breakpoint was not hit…

What I would of expected to happen would be the debugger break just as the page is loaded. It didn’t.

When my application builds, I have post-build events that copy required files (.aspx, bin dir etc…) to a separate directory, and i use a custom web server for the project (rather than the standard, local IIS Web server)

What this means is that the Global.asax file needs to be in my output directory.

Nothing in the “Global” class will run without the presence of the Global.asax file.

My post-build events did not copy *.asax files.

Upon adding this line, the issue was fixed, and my breakpoint is now hit.