Scott Hanselman

Mixing Razor Views and WebForms Master Pages with ASP.NET MVC 3

January 26, 2011 Comment on this post [16] Posted in ASP.NET | ASP.NET MVC | VS2010
Sponsored By

I've spent the last few weeks travelling around presenting WebMatrix, Razor and ASP.NET MVC 3 to folks. Many people have existing WebForms apps or MVC apps with WebForms Views. The question has come up a number of times, "Can I mix Razor Views and WebForms Views in a single ASP.NET MVC application?"

The answer is, "No, Yes, and Maybe, But It's Not Supported."

Most commonly the scenario is that someone has an existing WebForms (ASPX) Master Page that works nicely, and they now want to include a few Razor pages in their application but don't want to maintain two effectively identical Master Pages (one for ASPX, one for Razor). They want to share their WebForms Master with both WebForms and Razor Views.

First, the No.

You can't directly have a Razor Layout with WebForms Views, or a WebForms Master with Razor Views. While the concepts are similar, layouts are not masters and the concepts aren't exactly interchangeable.

Second, the Yes.

However, Html.RenderPartial or Html.RenderAction is an opportunity to move between view engines. As Eilon Lipton says, the idea of a partial view or controller action is a first-class concept in ASP.NET MVC, but master pages are implementation details of the specific view engines.

You can put shared content in Partials then call them from wherever. For example, from Eilon's suggestion, let's say you had these three WebForms partial views:

  • Header.ascx: Contains top navigation, menu, etc.
  • Footer.ascx: Contains copyright notice, privacy link, etc.
  • SearchBox.ascx: Contains search box implementation.

Then you have a basic WebForms master that references the above three user controls.

  • WebFormLayout.master: Lays out with the controls from above.
  • Page1.aspx: Uses WebFormLayout.master.
  • Page2.aspx: Uses WebFormLayout.master.
  • Page3.aspx: Uses WebFormLayout.master.

Then let's say you have a Razor Layout (Razor Layouts are like WebForms Masters) that reference to the same three WebForm user controls.

  • _RazorLayout.cshtml: Lays out with the controls from above.
  • Page4.cshtml: Uses _RazorLayout.cshtml.
  • Page5.cshtml: Uses _RazorLayout.cshtml.
  • Page6.cshtml: Uses _RazorLayout.cshtml.

This is the cleanest, easiest, and most supported way for doing things. You will have to have some minimal duplication between your Razor Layout and your WebForms Master, but most of the shared content is in the .ascx partials. You can mix this up as you like, but you get the idea.

Maybe, But It's not Supported

Matt Hawley from CodePlex took a look at this problem and blogged about his own solution for CodePlex. While it might feel like this should be a simple task, it's tricky because WebForms builds up a control tree and then renders it, while Razor is an all new system that's closer to a single pass template. Matt wants to directly share a WebForms Master page.

His solution is

  1. There's a web forms master page
  2. There's a web forms view page called "RazorView" in the \Shared folder
  3. The aspx view renders a partial in the content placeholder that is the actual razor view
  4. There are some new added RazorView extension methods for the controller that return a ViewResult.

Seems complex, but it's actually pretty straightforward. For example to get output like this browser screenshot using Matt's technique...

image

...we start with our WebForms View Site.Master:

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
</head>
<body>
<div>
<h1>I'm a WebForms Site.Master Page View. Seriously.</h1>
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
</body>
</html>

This is a normal master page. Here's our also normal Index.cshtml (Razor).

<h3>This is the index page. I'm Razor. We've clearly broken some kind of law to be at this point, right?</h3>

This page is basically nothing, and doesn't have a layout or anything specified. 

However, Matt has some extension methods he's added to the Controller class. Instead of returning View() from his controller action, he returns RazorView() like this.

public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
return this.RazorView();
}
}

Just a reminder as it begs repeating, RazorView is an extension method. Here's the whole ControllerExtensions class from Matt.

public static class ControllerExtensions
{
public static ViewResult RazorView(this Controller controller)
{
return RazorView(controller, null, null);
}

public static ViewResult RazorView(this Controller controller, object model)
{
return RazorView(controller, null, model);
}

public static ViewResult RazorView(this Controller controller, string viewName)
{
return RazorView(controller, viewName, null);
}

public static ViewResult RazorView(this Controller controller, string viewName, object model)
{
if (model != null)
controller.ViewData.Model = model;

controller.ViewBag._ViewName = GetViewName(controller, viewName);

return new ViewResult
{
ViewName = "RazorView",
ViewData = controller.ViewData,
TempData = controller.TempData
};
}

static string GetViewName(Controller controller, string viewName)
{
return !string.IsNullOrEmpty(viewName)
? viewName
: controller.RouteData.GetRequiredString("action");
}
}

Matt's solution is clever in its simplicity. When he calls RazorView() he's returning a ViewResult that's a WebForm View, even though we want a Razor one. This satisfies the whole WebForms master pages system. However, the WebForms view called "RazorView" exists for only one reason. It calls RenderPartial, as that's the right way too switch between view engines.

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>I'm a secret WebForms View that lies to everyone and renders Razor stuff. Ssssh! Delete this line!</h2>
<% Html.RenderPartial((string) ViewBag._ViewName); %>
</asp:Content>

Of course, when you use this, remove the <h2>, that's just for illustration. This view is only a shim that enables the switch.

So there you go. Two good options for mixing WebForms and Razor in your ASP.NET MVC application. The first has a little duplication, but is clean. The second is a little trickier and you're on your own, but you can directly share Master Pages between WebForms and Razor Views. You can get the code for the second over at Matt's blog.

Thanks Eilon and Matt!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Hanseminutes Podcast 249 - On WebMatrix with Rob Conery

January 22, 2011 Comment on this post [4] Posted in Podcast | WebMatrix
Sponsored By

image Microsoft WebMatrix was released on the 13th of January. Some folks have said its very existence is confusing. Do we need another IDE? What's Microsoft trying to pull here? Scott talks to ex-Microsoftie Rob Conery on his unfiltered take.

Download: MP3 Full Show

Links from the Show

NOTE: If you want to download our complete archives as a feed - that's all 249 shows, subscribe to the Complete MP3 Feed here.

Also, please do take a moment and review the show on iTunes.

Subscribe: Subscribe to Hanselminutes or Subscribe to my Podcast in iTunes or Zune

Do also remember the complete archives are always up and they have PDF Transcripts, a little known feature that show up a few weeks after each show.

Telerik is our sponsor for this show.

Building quality software is never easy. It requires skills and imagination. We cannot promise to improve your skills, but when it comes to User Interface and developer tools, we can provide the building blocks to take your application a step closer to your imagination. Explore the leading UI suites for ASP.NET AJAX,MVC,Silverlight,Windows Forms and WPF. Enjoy developer tools like .NET Reporting, ORM, Automated Testing Tools, Agile Project Management Tools, and Content Management Solution. And now you can increase your productivity with JustCode, Telerik’s new productivity tool for code analysis and refactoring. Visit www.telerik.com.

As I've said before this show comes to you with the audio expertise and stewardship of Carl Franklin. The name comes from Travis Illig, but the goal of the show is simple. Avoid wasting the listener's time. (and make the commute less boring)

Enjoy. Who knows what'll happen in the next show?

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Hanselminutes Podcast 248 - Executable Specifications with Gojko Adzic, Jonas Bandi and Aslak Hellesoy

January 22, 2011 Comment on this post [0] Posted in Agile | Podcast
Sponsored By

Aslak Hellesoy, Jonas Bandi and Gojko Adzic This week Scott learns about Executable Specifications with Gojko Adzic, Jonas Bandi and Aslak Hellesoy. What's all this talk about BDD, Cucumber, Gerkin and SpecFlow? Where's the best place to start and how to Acceptance Tests fit into my existing projects?

Download: MP3 Full Show

Links from the Show

NOTE: If you want to download our complete archives as a feed - that's all 247 shows, subscribe to the Complete MP3 Feed here.

Also, please do take a moment and review the show on iTunes.

Subscribe: Subscribe to Hanselminutes or Subscribe to my Podcast in iTunes or Zune

Do also remember the complete archives are always up and they have PDF Transcripts, a little known feature that show up a few weeks after each show.

Telerik is our sponsor for this show.

Building quality software is never easy. It requires skills and imagination. We cannot promise to improve your skills, but when it comes to User Interface and developer tools, we can provide the building blocks to take your application a step closer to your imagination. Explore the leading UI suites for ASP.NET AJAX,MVC,Silverlight,Windows Forms and WPF. Enjoy developer tools like .NET Reporting, ORM, Automated Testing Tools, Agile Project Management Tools, and Content Management Solution. And now you can increase your productivity with JustCode, Telerik’s new productivity tool for code analysis and refactoring. Visit www.telerik.com.

As I've said before this show comes to you with the audio expertise and stewardship of Carl Franklin. The name comes from Travis Illig, but the goal of the show is simple. Avoid wasting the listener's time. (and make the commute less boring)

Enjoy. Who knows what'll happen in the next show?

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Link Rollup: New Documentation and Tutorials from Web Platform and Tools

January 15, 2011 Comment on this post [11] Posted in ASP.NET | ASP.NET MVC | VS2010
Sponsored By

Lots of cool stuff was released yesterday that I mentioned in the post ASP.NET MVC3, WebMatrix, NuGet, IIS Express and Orchard released - The Microsoft January Web Release in Context. The Web Platform & Tools Content Team has been working hard on new content and tutorials to get you up to date on all this fun new stuff.

Here's a link rollup from Wade's documentation team. Congratulations to Mike Pope, Tim Teebken, Rick Anderson, Tim Ammann, Keith Newman, Erik Reitan and Tom Dykstra on a great set of content.

Read on!

Web Matrix

Tim Amman (Lead Writer), Erik Reitan and Mike Pope (Editor)

ASP.NET Web Pages with Razor Syntax

Tim Teebken (Lead Programming Writer), Erik Reitan,  and Mike Pope (Editor)

Intro to ASP.NET MVC 3 onboarding series.

Scott Hanselman and Rick Anderson collaboration and Mike Pope (Editor)

Both C# and VB versions:

MVC 3

Updated and new tutorials/ API Reference on MSDN

Rick Anderson (Lead Programming Writer), Keith Newman and Mike Pope (Editor)

Orchard 

Keith Newman (Lead Programming Writer), Tom FitzMacken and Mike Pope (Editor)

NuGet 

Tom Dykstra, Tim Teebken and Mike Pope (Editor))

Website Panel

Mike Pope provided editing support for the WebsitePanel Guide, authored by the Website Panel development team.

Enjoy!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

ASP.NET MVC3, WebMatrix, NuGet, IIS Express and Orchard released - The Microsoft January Web Release in Context

January 13, 2011 Comment on this post [35] Posted in ASP.NET | ASP.NET MVC | IIS | Microsoft | NuGet | Open Source | VS2010 | WebMatrix
Sponsored By

image At PDC10 last November I did a talk on the "Unnamed Package of Web Love", showing ASP.NET MVC3 and Razor Syntax, the NuGet Package Manager, as well as SQL Compact Edition and a little "Entity Framework Magic Unicorn." I make up my own names when I don't like what Microsoft names things, as you may notice.

Today Microsoft announced the (actual, final, honest) releases of:

  • ASP.NET MVC3 with Razor
    • Lots of new features, the new Razor syntax, more extensibility hooks, new JavaScript features, better validation, easier caching, better dynamic support, and lots more.
    • This includes the NuGet package manager and the NuGet gallery is also in early beta at http://nuget.org for folks who want to create and publish their own packages)
    • MVCScaffolding
      • Remember all that fun we had with the scaffolding experiment at PDC? Well, my teammate Steve Sanderson has taken the prototype up to version 0.8, and it's pretty fabulous. Go read his blog post, then enjoy "Install-Package MvcScaffolding." You can scaffold views, controllers, repositories, database contexts or even make your own custom scaffolder. Look for more built on scaffolding from Steve and I in the coming months.
    • Updated Beginner Tutorials for ASP.NET MVC 3 in both C# and in VB
  • NuGet
    • NuGet is a package manager for .NET. It ships with ASP.NET MVC, but you can go get it separately if you like. Installing open source libraries is as simple as "install-package elmah" - it's great fun.
  • WebMatrix (also with Razor)
    • WebMatrix is a small development environment that uses the simple Razor syntax to create websites really quickly. You can start from a gallery of existing open source applications or start from scratch. For example, Rob Conery and I wrote the little podcast site and feed for http://thisdeveloperslife.com in a day with WebMatrix.
    • NuGet package management is built into WebMatrix, too! Make a new site, run it, and hit /_admin. Dance.
  • IIS 7.5 Express
    • Yes, you can install it on its own. It's IIS, except it runs as a user process rather than a service. Cassini (Visual Developer Web Server) is dead! It's "just in time" IIS. There when you need it, and not running when it's not used.
    • This is the web server that Web Matrix uses today, but it'll be enabled in Visual Studio 2010 when SP1 comes out.
  • SQL Compact Edition 4
    • SQL Compact Edition is sweet because is a tiny in-process (no services, don't need to be admin) database that's great for small sites that aren't ready for SQL Server proper. It's xcopy-deployable and runs nicely on hosted sites. It's the default database for WebMatrix and I'm using it in Visual Studio for sites where my database isn't big enough to justify a SQL license.
    • You can use SQL Compact today in Visual Studio at runtime, much like I did in my PDC talk, but you won't be able to design and open your database in VS until SP1. (You can use this Non-MS CodePlex project temporarily, but I didn't tell you.)
  • Web Farm Framework 2.0 and Web Deploy
    • Makes setting up multiple servers way easier. Treat and manage groups of servers, use ARR for load-balancing (or use 3rd party balancers), and upgrade, switch, and add servers with PowerShell. Mmm....PowerShell.
  • Orchard 1.0
    • This free, open-source content management system is ready to go. The release is published on the Orchard CodePlex website and Microsoft Web Application Gallery. You can use Orchard all up, or you can take it apart and just use pieces. Mix and match as you like.

It's the January Web Release, say I, and the easiest way to get it is with Web Platform Installer 3.0, which also went live today. Using direct links to products within the Web Platform installer will automatically add any dependencies you might need.

Now what? I'm freaking out!

Folks sometimes say "slow down, you're freaking me out, this is too much new stuff. What about my current stuff?" Here's a few statements from me personally on today's releases.

  • Just because ASP.NET MVC 3 came out today, doesn't mean WebForms doesn't have some cool features coming. Remember that "ASP.NET > ASP.NET MVC". You'll see features and improvements from both technologies move between MVC and WebForms.
  • IIS Express will integrate with VS2010 in SP1 and work with both WebForms and MVC.
  • You can mix Razor Views and Web Forms Views within MVC. The creation/existence of Razor doesn't obviate your existing work.
  • SQL Compact works great with WebForms as well as ASP.NET MVC, not to mention any .NET project. Ever want a tiny database for a command-line app and didn't want the headache? Bam.
  • SQL Compact database can be upgraded into full SQL Server databases when/if you outgrow SQL Compact.
  • While NuGet is bundled with ASP.NET MVC in today's release, you can use it for any .NET project type. Most NuGet libraries are not specific to ASP.NET MVC.

As I've said before, Microsoft is creating new LEGO pieces for software development to round our existing collection of bricks out. Be exited about these bricks, but remember they augment the existing ones, not replace them.

What now?

I'd recommend you go get MVC3 and WebMatrix, preferably at the same time via one of these Web Platform links. That should get you all these other nice things chained in. In the spring when VS2010 SP1 comes out, the tooling and management bits for SQL Compact and IIS Express will be enabled.

Stuff to Get

ReSharper Updated

One other note, the folks at JetBrains were ready for this and spun a new build of ReSharper, so ReSharper 5.1.2 doesn’t interfere with Visual Studio IntelliSense in ASP.NET MVC 3 Razor syntax. Earlier ReSharper 5.x builds had certain issues with Razor IntelliSense that are addressed in 5.1.2. Specifically, ReSharper 5.1.2 doesn’t prevent Visual Studio from automatically providing its own IntelliSense in .cshtml and .vbhtml web pages anymore: both code completion and Parameter Info work as expected. Other than that, ReSharper 5.x doesn’t provide any additional support for Razor: only ReSharper 6 will bring full support for this view engine. Pre-release ReSharper 6 builds are currently available via Early Access Program, so if you're a ReSharper user, be aware!

Enjoy.

Related Links

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.