views:

525

answers:

2

Is it possible to use Razor on an existing Asp.Net 4 WebSite?

+8  A: 

Yes, you can use Razor with an existing ASP.NET WebSite. Simply open your website using the WebMatrix tool and start adding CSHTML files. One caveat is that if your website is using WebForms controls the WebMatrix tool will not provide any help working with them in existing aspx pages. Additionally, Razor does not support WebForms so you will not be able to add something like <asp:GridView> to a CSHTML file.

marcind
+1  A: 

marcind is correct, if you want to open your existing ASP.NET website in WebMatrix and work on it from within the tool. If, on the other hand (or in addition to), you want to use Razor syntax in your site and stay within VisualStudio, check out this article: http://weblogs.asp.net/rashid/archive/2010/07/10/use-razor-as-asp-net-mvc-viewengine.aspx

There are four things you need to do:

  1. Add References to the Razor assemblies installed with WebMatrix. These can be found at C:\Program Files\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies

  2. Create a custom ViewEngine class, a View class that inherits from IView (not that hard, check out the source in the article above)

  3. Add your new ViewEngine in Global.asax Application_Start()

    ViewEngines.Engines.Add(new RazorViewEngine(("cs"));
    
  4. Create your view pages with a .cshtml extension, instead of .aspx

There are a few steps here, but it's quick work, and the source from the article above will get you a long way there.

Brandon Satrom
The viewengine in that blog post does not actually work so please don't use it. Also, it only applies to ASP.NET MVC proejcts anyway.
marcind
@marcind What specific problems did you have with it? I tried it out myself before suggesting it and didn't have any issues, but it would be good to know what problems you had so I can avoid pointing folks to it in the future.As for you're second point, true enough. I think I assumed too much from the question, where your answer was correct.
Brandon Satrom
Things like `using (Html.BeginForm())` do not work and other things related to rendering of partial views.
marcind