Posts in "Razor" tag

Import Namespaces for Razor Views

Posted on 28 July 2010 and tagged with , 0 comments

Previously when developing with the WebForms view engine we could use the Web.config file to import namespaces where we stored our extension methods or models. They would then be available to all our views without having to explicitly declare them in each view.

In Razor this is no longer possible due to how it’s built, which is why we have to manually register them in the Application_Start event.

To do this begin with opening Global.asax and create a new method called RegisterGlobalImports, and call it from the Application_Start method. In the newly created method you add all the namespaces you wish to have in your view by calling AddGlobalImport on CodeGeneratorSettings.

public static void RegisterGlobalImports() {
    CodeGeneratorSettings.AddGlobalImport("MvcApplicationRazor.Core.Extensions");
    CodeGeneratorSettings.AddGlobalImport("MvcApplicationRazor.Core.Models");
}

protected void Application_Start() {
    RegisterGlobalImports();
    
    AreaRegistration.RegisterAllAreas();            
    RegisterRoutes(RouteTable.Routes);
}

I usually register extension methods, that should be available in the view, and models so I won’t have to type namespaces over and over again.

Read More »

Getting HTML Colorization with Razor View Engine

Posted on 27 July 2010 and tagged with , , 0 comments

imageToday the Gu announced the first preview of ASP.NET MVC 3, which included the new Razor view engine. I’ve been really excited about it as I feel it makes our views a lot prettier than before with Web Forms view engine. It will also be a lot quicker and smoother to type without all those messy <%-characters.

To the point! I am currently upgrading an existing site to use MVC 3 and Razor. However in this first preview of MVC 3 we won’t have any File Colorization or IntelliSense in .cshtml files. This means it will look like we’re editing in Notepad. It got me wondering if there was a way to at least get some colorization, more specifically HTML colorization. I wandered around in the options of VS2010, and eventually found the place where I could map an extension to a different colorization.

This is how you get HTML colorization in .cshtml files:

  1. Open Tools menu.
  2. Choose Options…
  3. Go to Text Editor, and third choice; File Extension.
  4. Enter cshtml as Extension and choose HTML Editor in the dropdown.
  5. Click Add and OK. Now try to open a .cshtml file – you should get HTML colorization.

Remember to remove this setting when VS2010 officially gets Razor colorization and IntelliSense.

That’s it. Hopefully it will be a little bit easier on your eyes.

Read More »

Loading Posts...