If you have a website which loads content dynamically using AJAX, you may be using hashbangs (#!) to indicate state. This method is popular due to the specification put together by google which translates the url fragment into a querystring parameter, and issues a request to the server to get an html snapshot of the state.

Below is an implementation of an EscapedFragmentRoute which allows you to map routes which include hashbangs to actions using the standard MVC routing infrastructure. Just include the hashbang in your route patterns, and this will match it, working off the assumption that the url fragment can be found in the _escaped_fragment_ querystring parameter.

I am using attribute routing with MVC 5.1 which allows you to write your own route generation attributes. The following attribute creates an EscapedFragmentRoute instead of the standard one. Note, if you go down this path, then you need to use this attribute on the main page too, otherwise you’ll find that multiple controllers/actions may match the url, and cause an error

If you have a partial view in MVC, it may be necessary to render scripts specific to this view, and a common approach is to include the scripts (not necessarily inline) in the html mark up of the view.

The problem with this is that you may be depending on library scripts which are not loaded yet because they are the last thing in your Layout/Master.

One option is to change the design so that rather than calling Html.Partial to render a partial view, the partial view becomes the view, and the view becomes a master/layout. You can now use DefineSection, RenderBody, RenderSection etc. This however was not an option for me for several reasons.

Here is the solution I came up with which will only work for rendering content at the end of the document. It won’t work for injecting content into the head (e.g. css) because it runs in the order you expect. The scripts are registered in during the call to Html.Partial, which (usually) comes after the head section, meaning the head section is already done and its too late. In fact, I have even named the functions BeginScripts and Html.PageScripts instead of something more generic to make it clear it is only really applicabale for scripts at the end of the page.

It shouldn’t take much work to improve the above code to operate more like the ClientScriptManager of asp.net… use a dictionary instead of a list, and require a key to verify the same script can’t be registered twice. Alternativly (what i’ve done in the project I’m working on), you could accept an optional list of library dependencies in BeginScripts, and simply make sure these have been rendered before outputting the scripts themseleves

Why does the ReadByte method of a stream return an int instead of a byte? According to reflector it is returning the first element of a byte array, implicitly casted to an int. I’m then casting this straight back to a byte… I’m not sure what the benefit is of this!