Introducing “Razor” – a new view engine for ASP.NET

One of the things my team has been working on has been a new view engine option for ASP.NET.

ASP.NET MVC has always supported the concept of “view engines” – which are the pluggable modules that implement different template syntax options.  The “default” view engine for ASP.NET MVC today uses the same .aspx/.ascx/.master file templates as ASP.NET Web Forms.  Other popular ASP.NET MVC view engines used today include Spark and NHaml.

The new view-engine option we’ve been working on is optimized around HTML generation using a code-focused templating approach. The codename for this new view engine is “Razor”, and we’ll be shipping the first public beta of it shortly.

Design Goals

We had several design goals in mind as we prototyped and evaluated “Razor”:

  • Compact, Expressive, and Fluid: Razor minimizes the number of characters and keystrokes required in a file, and enables a fast, fluid coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote server blocks within your HTML. The parser is smart enough to infer this from your code. This enables a really compact and expressive syntax which is clean, fast and fun to type.

  • Easy to Learn: Razor is easy to learn and enables you to quickly be productive with a minimum of concepts. You use all your existing language and HTML skills.

  • Is not a new language: We consciously chose not to create a new imperative language with Razor. Instead we wanted to enable developers to use their existing C#/VB (or other) language skills with Razor, and deliver a template markup syntax that enables an awesome HTML construction workflow with your language of choice.

  • Works with any Text Editor: Razor doesn’t require a specific tool and enables you to be productive in any plain old text editor (notepad works great).

  • Has great Intellisense: While Razor has been designed to not require a specific tool or code editor, it will have awesome statement completion support within Visual Studio. We’ll be updating Visual Studio 2010 and Visual Web Developer 2010 to have full editor intellisense for it.

  • Unit Testable: The new view engine implementation will support the ability to unit test views (without requiring a controller or web-server, and can be hosted in any unit test project – no special app-domain required).

We’ve spent the last few months building applications with it and doing lots of usability studies of it with a variety of volunteers (including several groups of non-.NET web developers). The feedback so far from people using it has been really great.

Choice and Flexibility

One of the best things about ASP.NET is that most things in it are pluggable. If you find something doesn’t work the way you want it to, you can swap it out for something else.

The next release of ASP.NET MVC will include a new “Add->View” dialog that makes it easy for you to choose the syntax you want to use when you create a new view template file.  It will allow you to easily select any of of the available view engines you have installed on your machine – giving you the choice to use whichever view approach feels most natural to you:

AddView9

Razor will be one of the view engine options we ship built-into ASP.NET MVC.  All view helper methods and programming model features will be available with both Razor and the .ASPX view engine. 

You’ll also be able to mix and match view templates written using multiple view-engines within a single application or site.  For example, you could write some views using .aspx files, some with .cshtml or .vbhtml files (the file-extensions for Razor files – C# and VB respectively), and some with Spark or NHaml.  You can also have a view template using one view-engine use a partial view template written in another.  You’ll have full choice and flexibility.

Hello World Sample with Razor

Razor enables you to start with static HTML (or any textual content) and then make it dynamic by adding server code to it.  One of the core design goals behind Razor is to make this coding process fluid, and to enable you to quickly integrate server code into your HTML markup with a minimum of keystrokes.

To see a quick example of this let’s create a simple “hello world” sample that outputs a message like so:

image

Building it with .ASPX Code Nuggets

If we were to build the above “hello world” sample using ASP.NET’s existing .ASPX markup syntax, we might write it using <%= %> blocks to indicate “code nuggets” within our HTML markup like so:

image

One observation to make about this “hello world” sample is that each code nugget block requires 5 characters (<%= %>) to denote the start and stop of the code sequence.  Some of these characters (in particular the % key – which is center top on most keyboards) aren’t the easiest to touch-type.

Building it with Razor Syntax

You denote the start of a code block with Razor using a @ character.  Unlike <% %> code nuggets, Razor does not require you to explicitly close the code-block:

image

The Razor parser has semantic knowledge of C#/VB code used within code-blocks – which is why we didn’t need to explicitly close the code blocks above.  Razor was able to identify the above statements as self-contained code blocks, and implicitly closed them for us.

Even in this trivial “hello world” example we’ve managed to save ourselves 12 keystrokes over what we had to type before.  The @ character is also easier to reach on the keyboard than the % character which makes it faster and more fluid to type. 

Loops and Nested HTML Sample

Let’s look at another simple scenario where we want to list some products (and the price of each product beside it):

image

Building it with .ASPX Code Nuggets

If we were to implement this using ASP.NET’s existing .ASPX markup syntax, we might write the below code to dynamically generate a <ul> list with <li> items for each product inside it:

image 

Building it with Razor Syntax

Below is how to generate the equivalent output using Razor:

image

Notice above how we started a “foreach” loop using the @ symbol, and then contained a line of HTML content with code blocks within it.  Because the Razor parser understands the C# semantics in our code block, it was able to determine that the <li> content should be contained within the foreach and treated like content that should be looped.  It also recognized that the trailing } terminated the foreach statement.

Razor was also smart enough to identify the @p.Name and @p.Price statements within the <li> element as server code – and execute them each time through the loop. Notice how Razor was smart enough to automatically close the @p.Name and @p.Price code blocks by inferring how the HTML and code is being used together.

The ability to code like this without having to add lots of open/close markers throughout your templates ends up making the whole coding process really fluid and fast.

If-Blocks and Multi-line Statements

Below are a few examples of other common scenarios:

If Statements

Like our foreach example above, you can embed content within if statements (or any other C# or VB language construct), without having to be explicit about the code block’s begin/end.  For example:

image

Multi-line Statements

You can denote multiple lines of code by wrapping it within a @{ code } block like so:

image 

Notice above how variables can span multiple server code blocks – the “message” variable defined within the multi-line @{ } block, for example, is also being used within the @message code block.  This is conceptually the same as the <% %> and <%= %> syntax within .aspx markup files.

Multi-Token Statements

The @( ) syntax enables a code block to have multiple tokens.  For example, we could re-write the above code to concatenate a string and the number together within a @( code ) block:

image 

Integrating Content and Code

The Razor parser has a lot of language smarts built-into it – enabling you to rely on it to do the heavily lifting, as opposed to you having to explicitly do it yourself. 

Does it break with email addresses and other usages of @ in HTML?

Razor’s language parser is clever enough in most cases to infer whether a @ character within a template is being used for code or static content.  For example, below I’m using a @ character as part of an email address:

image

When parsing a file, Razor examines the content on the right-hand side of any @ character and attempts to determine whether it is C# code (if it is a CSHTML file) or VB code (if it is a VBHTML file) or whether it is just static content.  The above code will output the following HTML (where the email address is output as static content and the @DateTime.Now is evaluated as code:

image

In cases where the content is valid as code as well (and you want to treat it as content), you can explicitly escape out @ characters by typing @@.

Identifying Nested Content

When nesting HTML content within an if/else, foreach or other block statement, you should look to wrap the inner content within an HTML or XML element to better identify that it is the beginning of a content block.

For example, below I’ve wrapped a multi-line content block (which includes a code-nugget) with a <span> element:

image

This will render the below content to the client – note that it includes the <span> tag:

image

You can optionally wrap nested content with a <text> block for cases where you have content that you want to render to the client without a wrapping tag:

image

The above code will render the below content to the client – note that it does not include any wrapping tag:

image 

HTML Encoding

By default content emitted using a @ block is automatically HTML encoded to better protect against XSS attack scenarios.

Layout/MasterPage Scenarios – The Basics

It is important to have a consistent look and feel across all of the pages within your web-site/application.  ASP.NET 2.0 introduced the concept of “master pages” which helps enable this when using .aspx based pages or templates.  Razor also supports this concept using “layout pages” – which allow you to define a common site template, and then inherit its look and feel across all the views/pages on your site.

Simple Layout Example

Below is a simple example of a layout page – which we’ll save in a file called “SiteLayout.cshtml”.  It can contain any static HTML content we want to include in it, as well as dynamic server code.  We’ll then add a call to the “RenderBody()” helper method at the location in the template where we want to “fill in” specific body content for a requested URL:

image

We can then create a view template called “Home.cshtml” that contains only the content/code necessary to construct the specific body of a requested page, and which relies on the layout template for its outer content:

image

Notice above how we are explicitly setting the “LayoutPage” property in code within our Home.cshtml file.  This indicates that we want to use the SiteLayout.cshtml template as the layout for this view.  We could alternatively indicate the layout file we want to use within a ASP.NET MVC Controller invoking Home.cshtml as a view template, or by configuring it as the default layout to use for our site (in which case we can specify it in one file in our project and have all view templates pick it up automatically).

When we render Home.cshtml as a view-template, it will combine the content from the layout and sub-page and send the following content to the client:

image

Compact, Clean, Expressive Code

One of the things to notice in the code above is that the syntax for defining layouts and using them from views/pages is clean and minimal.  The code screen-shots above of the SiteLayout.cshtml and Home.cshtml files contain literally all of the content in the two .cshtml files – there is no extra configuration or additional tags, no <%@ Page%> prefix, nor any other markup or properties that need to be set.

We are trying to keep the code you write compact, easy and fluid.  We also want to enable anyone with a text editor to be able to open, edit and easily tweak/customize them.  No code generation or intellisense required.

Layout/MasterPage Scenarios – Adding Section Overrides

Layout pages optionally support the ability to define different “sections” within them that view templates based on the layout can then override and “fill-in” with custom content.  This enables you to easily override/fill-in discontinuous content regions within a layout page, and provides you with a lot of layout flexibility for your site.

For example, we could return to our SiteLayout.cshtml file and define two sections within our layout that the view templates within our site can optionally choose to fill-in.  We’ll name these sections “menu” and “footer” – and indicate that they are optional (and not required) within our site by passing an optional=true parameter to the RenderSection() helper call (we are doing this using the new C# optional parameter syntax that I’ve previously blogged about).

image

Because these two sections are marked as “optional”, I’m not required to define them within my Home.cshtml file.  My site will continue to work fine if they aren’t there. 

Let’s go back into Home.cshtml, though, and define a custom Menu and Footer section for them.  The below screenshot contains all of the content in Home.cshtml – there is nothing else required in the file.  Note: I moved setting the LayoutPage to be a site wide setting – which is why it is no longer there.

image

Our custom “menu” and “footer” section overrides are being defined within named @section { } blocks within the file.  We chose not to require you to wrap the “main/body” content within a section and instead to just keep it inline (which both saves keystrokes and enables you to easily add sections to your layout pages without having to go back through all your existing pages changing their syntax). 

When we render Home.cshtml as a view-template again, it will now combine the content from the layout and sub-page, integrating the two new custom section overrides in it, and send down the following content to the client:

image

Encapsulation and Re-Use with HTML Helpers

We’ve covered how to maintain a consistent site-wide look and feel using layout pages.  Let’s now look at how we can also create re-usable “HTML helpers” that enable us to cleanly encapsulate HTML generation functionality into libraries that we can re-use across our site – or even across multiple different sites.

Code Based HTML Helpers

ASP.NET MVC today has the concept of “HTML Helpers” – which are methods that can be invoked within code-blocks, and which encapsulate generating HTML.  These are implemented using pure code today (typically as extension methods).  All of the existing HTML extension methods built with ASP.NET MVC (both ones we’ve built and ones built by others) will work using the “Razor” view engine (no code changes required):

image

Declarative HTML Helpers

Generating HTML output using a code-only class approach works – but is not ideal.

One of the features we are looking to enable with Razor is an easy way to create re-usable HTML helpers using a more declarative approach.  Our plan is to enable you to define reusable helpers using a @helper { } declarative syntax like below. 

image

You’ll be able to place .cshtml files that contain these helpers into a Views\Helpers directory and then re-use them from any view or page in your site (no extra steps required):

image

Note above how our ProductListing() helper is able to define arguments and parameters.  This enables you to pass any parameters you want to them (and take full advantage of existing languages features like optional parameters, nullable types, generics, etc).  You’ll also get debugging support for them within Visual Studio.

Note: The @helper syntax won’t be in the first beta of Razor – but is something we hope will be enabled with the next drop.  Code-based helpers will work with the first beta.

Passing Inline Templates as Parameters

One other useful (and extremely powerful) feature we are enabling with Razor is the ability to pass “inline template” parameters to helper methods.  These “inline templates” can contain both HTML and code, and can be invoked on-demand by helper methods.

Below is an example of this feature in action using a “Grid” HTML Helper that renders a DataGrid to the client:

image

The Grid.Render() method call above is C#.  We are using the new C# named parameter syntax to pass strongly-typed arguments to the Grid.Render method - which means we get full statement completion/intellisense and compile-time checking for the above syntax.

The “format” parameter we are passing when defining columns is an “inline template” – which contains both custom html and code, and which we can use to customize the format of the data.  What is powerful about this is that the Grid helper can invoke our inline template as a delegate method, and invoke it as needed and as many times as it wants. In the scenario above it will call it each time it renders a row in the grid – and pass in the “item” that our template can use to display the appropriate response.

This capability will enable much richer HTML helper methods to be developed.  You’ll be able to implement them using both a code approach (like the way you build extension methods today) as well as using the declarative @helper {} approach.

Visual Studio Support

As I mentioned earlier, one of our goals with Razor is to minimize typing, and enable it to be easily edited with nothing more than a basic text editor (notepad works great).  We’ve kept the syntax clean, compact and simple to help enable that.

We have also designed Razor so that you get a rich code editing experience within Visual Studio.  We will provide full HTML, JavaScript and C#/VB code intellisense within Razor based files:

image

Notice above how we are providing intellisense for a Product object on the “@p.” code embedded within the <li> element inside a foreach loop.  Also notice how our \Views folder within the Solution Explorer contains both .aspx and .cshtml view templates.  You can use multiple view engines within a single application – making it easy to choose whichever syntax feels best to you.

Summary

We think “Razor” provides a great new view-engine option that is streamlined for code-focused templating.  It a coding workflow that is fast, expressive and fun.  It’s syntax is compact and reduces typing – while at the same time improving the overall readability of your markup and code.  It will be shipping as a built-in view engine with the next release of ASP.NET MVC.  You can also drop standalone .cshtml/.vbhtml files into your application and run them as single-pages – which also enables you to take advantage of it within ASP.NET Web Forms applications as well.

The feedback from developers who have been trying it out the last few months has been extremely positive.  We are going to be shipping the first public beta of it shortly, and are looking forward to your feedback on it.

Hope this helps,

Scott

P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

270 Comments

  • Holy crap Scott... that's dope!!! I'm definitely interested in making the leap.

  • Nice work guys, this looks really cool.

  • This is totally awesome! Damnit you guys are just too good!

  • Wow!

    So this is what Luis was up to?!

  • Very nice. This looks like a real step forward.

  • WoW - this is some cool stuff. Please get it out ASAP :)

  • Scott,

    Unit-testing views is challenging. Could you please give us some information about the way of unit-testing razor views?





  • Will you be building out a full set of snippets with Razor as well to speed things up just that little bit more?

  • This is super awsum...... I am in Love....

  • Incredible work... thank you. Waiting eagerly for the drop!
    How about some conditional output like: generate this HTML if/unless X is true?

  • Thanks Scott! What can you tell us at this time about the performance of the Razor view engine compared to the WebForms view engine?

  • I'm trying to see from these examples exactly how this will enable unit testing of our views in ASP.NET MVC.

    Will the Razor views be executable outside of the normal ASP.NET page lifecycle, maybe by at least calling a "toString()" on them or executing them by stubbing out a "Render" method on the view engine?

    Also, if we can use standard C# syntax in our views, I'm assuming we can use expressions and lambdas directly in our views?

  • Very nice article. Thanks! The % is pretty hard to type :)

  • @syntaxc4,

    >>>>>>> Will you be building out a full set of snippets with Razor as well to speed things up just that little bit more?

    Yes - we will provide snippet support as well for Razor.

    Hope this helps,

    Scott

  • @Roland, @Skoon

    >>>>>>>> Unit-testing views is challenging. Could you please give us some information about the way of unit-testing razor views?

    The Razor parser and view engine can be instantiated and used outside of the ASP.NET application domain. This means you can directly instantiate and use it within a unit test project without any dependencies on running ASP.NET.

    From a unit testing perspective you can indicate the view template you want to run, supply it with any dependencies, and then pass your own test models/viewmodels to it and have it run and render back a string to you. You could then verify that the correct content came back. This would isolate the views from your controllers and any data access, and allow you to also isolate them from the runtime environment. View engines in ASP.NET MVC VNext (both Razor and the .ASPX one) will also support and integrate with dependency injection as well.

    Different people have differing opinions about the usefulness of verifying the HTML that comes back from a view using unit tests. For scenarios involving a lot of javascript something like browser based testing is probably better. But for basic coverage it can be useful. It also helps verify that you don't have compile errors or other runtime boundary errors with your views.

    Hope this helps,

    Scott

  • Scott, I was expecting improvements to the view design experience for MVC 3, but this is ALOT more than expected. This looks fun.

    Really like the idea of the @helper syntax. Is it same to assume that this will support inline templates?
    (I made my own MVC 2 implementation of this using Action delegates and Partials - it is a big time saver.)




  • This is just what I have been looking for, it looks fantastic. I can't wait to get my hands on a Beta.

    Rich

  • @Scott Koon,

    >>>>>>> Also, if we can use standard C# syntax in our views, I'm assuming we can use expressions and lambdas directly in our views?

    Yes - you get to use every feature in C# - including expressions and lambdas. Combined with the razor syntax this allows some pretty expressive things.

    BTW - check above and I combined your unit testing question with another answer i gave.

    Hope this helps,

    Scott

  • @lynn,

    Glad u like it!

    >>>>>> Really like the idea of the @helper syntax. Is it same to assume that this will support inline templates?

    Yes - that should support inline templates as well. Note that the @helper syntax is the only thing in the post not in the beta - everything else is already implemented. The @helper stuff comes next.

    Hope this helps,

    Scott

  • @James,

    >>>>>>>> Thanks Scott! What can you tell us at this time about the performance of the Razor view engine compared to the WebForms view engine?

    Razor is fully compiled - so the performance should be great.

    Hope this helps,

    Scott

  • will I be able to use this view engine in a standalone console app to generate HTML?
    Can I simply instantiate a new view passing it the path to the chtml file and my model, and then call render on it to build the HTML?
    I suppose that's what you mean by nit testable... :)

  • @stephane,

    >>>>>>>> will I be able to use this view engine in a standalone console app to generate HTML? Can I simply instantiate a new view passing it the path to the chtml file and my model, and then call render on it to build the HTML? I suppose that&#39;s what you mean by unit testable... :)

    Yep - that scenarios is fully possible.

    Hope this helps,

    Scott

  • You've just blown every other templating engine/language out of the water. This looks like a very solid well designed implementation.

  • Is it just me or the main change here is to replace the crazy with @ sign?

  • what about code in attributes? will intellisense be given in that situation unlike webforms

  • Hi Scott, in the old way, we can declare strongly-type ViewData for a view using , how about in Razor?

  • Cool.
    I'm very like that you "chose not to create a new imperative language with Razor" — this is why I feel another view-engines not so natural for me.

    What about intellisese in html attributes? Today .aspx intellisense didn't work when I'm typing something like this: <tr class="">..., but this works and my feel is that intellisense isn't complete with this.

  • niiice
    but what about <%= and <%:
    does razor can understand the diffrance between those 2?

  • Great view engine.
    Less block, Nicer view.

  • I'm going to use it! Looks very good!

  • How does all this work when you use Expression Web to edit some of your HTML.

    Also is this going to render nicely in Visual Studio Express?

    p.s. I really like RAZOR !!!

  • That's awesome, I'd like to develop my new project with this new view engine!

  • This is sooo awesome!

    Keep up the good work!

    /Mikael Söderström

  • Wow!.. You should release the beta ASAP!

    The C#-based code-interpolation is great and yet, being able to use it outside of ASP.NET is even better!

  • RAZOR sounds good. How about MVC-specific server controls that are totally unbound from the postback and view-state ????

  • Awesome job!!! I'm really like Razor too!!

  • Much needed improvement

  • Hi,

    Its a sad day for us WebForms developers that such a thing wont exist there or so I think because you havent talked about that in the post atleast,so how can we use it in Web Forms?

  • I bet that Louis DeJardin worked on this.

    Anyway - nice job.

  • That is great. I like it very much.

  • This is awesome news, I can't wait to work with it. Will there be a ctp?

  • Fantastic work Scott and team.

    Something I have become very fond of is the terseness of NHaml, particularly in terms of HTML. Not having to close every tag and replacing that concern with simple indentation is just awesome. All that brackety stuff is just so noisy ;)

    Is this something you would consider for Razor?

    Thanks again, awesome addition to an already brilliant platform.

    Q

  • Thanks Scott - I used NVelocity for 'mail merge' type functionality - I'm glad this was done so it can be independent of asp.net - this way, it will be a great template engine for all C# needs.

    Great work by your team! I'm glad to see the efforts toward asp.net mvc. I'm on my 3rd application with it, and it's been great to work with.

    Thanks again!

  • Really nice view engine!
    Like the good readable views with this engine.
    It's clear and not to much overkill.

    Thumbs up!

  • Awesome...very nice!

  • This is kick-ass!
    Question - will there be any sort of support for dynamic compilation of the template pages? For example, take a CMS web app, the users of the app are allowed to edit these templates, store them in a DB as text, and then the app needs to compile and use them on demand.
    This is something I can't seem to do now in regular ASP.NET.

  • Hi Scott, Its amaizing to have another view engine and coming from the MS team. You're using in the first code sample the following code:
    /products/details/@productID instead of Html.ActionLInk or Url.Action.
    MS has made some amaizing moves in the web field and we need to teach to use it properly and using this kind of code don´t help to understand some of this amaizing features MS is doing.
    Best
    Juan

  • ScottGu 2012. He has my vote :-)

    Ok. Let's not get too carried away; but this is a welcome surprise. This entire week was a welcome surprise. Can't wait to try this out.

  • Some of the examples above remind me of working with XML literals to generate HTML. XML Literals are very underrated feature in .net for generating HTML. Will VB's XML literals play nicely with Razor?

  • I'm very very excited to begin to use the Razor.
    I've a question: Will we be able to use nested Master/LayoutPages?

    THANKS

  • @h1 Single Line Statement?
    @h2 Why not generalize the thing further?

    @p {
    ...and save @a { href="" even more } keystrokes?
    }

    @span { class="sig" Axel }


  • This is certainly an improvement to the syntax we use everyday, but I still have a lot of questions:

    *How do you prevent HTML encoding?

    *Do the layouts support nesting?

    *If they do support nesting, do they support inherited sections? That is, can a view two levels deep contribute to filling in a section from its grandparent layout? Something like: @RenderSection("metadata", optional:true, passthrough:true)

    *Are there any specific improvements to help us register scripts/stylesheets from lower down the layout hierarchy or set the page title?

    *Any special syntax/conventions for partials?

    *Is there any special support for loops where the collection is empty, such as rendering an alternate set of data?


    This looks great though, and I'm quite happy to see you guys innovating. I just hope this can be more than WebForms with prettier markup and really offer us new ways of coding views.

  • How do you declare a strongly typed viewmodel?
    When is the view compiled - at build time, or runtime? Specifically, is there a backing type (like WebForms codebehind) that is discoverable at app startup time, or is the type compiled on the fly (like an aspx template)?

  • @Scott, will you release it on CodePlex but at least with Source Code? That should be awesome!

    I'm interested in what parser tool you used to create this beauty :-)

    Thanks,
    Attila

  • This will make me actually give MVC another try. You guys have addressed the primary issue that I had which was "This MVC coding is taking me too long".

    However, I am still waiting for more tooling. The reason I am so happy with Silverlight coding is that Expression Blend gives me superior tooling for the UI. When I see you knock out a great looking UI in MVC easily I will be willing to commit at least 100 hours to try to learn it again.

  • When I saw this in MVC at first I thought oh god no, I hate this in MVC, its just horrible.

    for loops in the front end in mvc = yuck!, its back to the bad old days of spaghetti code in the old asp world.

    Thumbs down for me I'm afraid.

  • Will Razor remove unneeded whitespace and/or html comments at compile-time, preferably through a setting?
    I think that would be a killer feature.

    At dev-time the html is nicely readable, at run-time a whitespace stripped version is streamed to the client.
    Also, more too often I find devs leaving commented html in the source which is streamed to the client too, unnecessarily ...

    // Ryan

  • @Scott - I love the direction you guys are going, but one of the things that draw people towards the alternate view engines is not only the syntax, but also the way it mingles with the HTML.

    One of the biggest complaints is the use of the "{ }" as well as "" syntax. I am not seeing much difference in this new syntax when compared to the old. It still ends up looking like spaghetti code, IMHO. How about something more like spark syntax? It mingles nicely with and into the HTML. And while on that subject, why not just endorse spark as an official view engine?

    Love the ideas you guys have coming out, please keep them coming.

  • is there any video lectures on asp.net..........
    Please inform me.

  • I tend to agree with Alec. The biggest problem is with the intermingling of "{}" and "". You can really see this with "foreach" and "if" and it's only marginally improved with the new view engine. It's definitely worth investigating what it would take to create a custom syntax for these two scenarios because they are so common and still difficult to read. Perhaps something like this:

    @p.Name (@p.Price)

    Use the html block as a designator of the foreach block scope. Here's another:

    Sorry - no products in this catagory
    We have products for you!

    By using the Html tags as the block delimiters, you can get rid of the "{}" and by embedding the flow control into the tag, the document's structure is visually preserved. For me, this is a lot easier to read.

    I really like the idea of declarative helpers and templating inlining. Automatic html encoding was a real need too. If we can clean up the "foreach" and "if" then I'll be happy.

  • I'd like to see some more Ajax love, less page-generation. :)

    (The jquery-tmpl stuff isn't moving as fast as I'd expected).

  • @NGoc,

    >>>>>>>>> Hi Scott, in the old way, we can declare strongly-type ViewData for a view using , how about in Razor?

    Yes - you can define strongly-typed models as well with Razor - in which case the Model property will be strongly typed within the template.

    Razor currently supports the ability to say:

    @inherits TypeNameOfBaseClass

    We are also considering supporting an option to just say:

    @Model ModelType

    as a shorter way to describe it as well.

    Hope this helps,

    Scott

  • Wow, awesome! Inline C# code without <% fells like magic :)

    How this simple example will look in the Razor engine;

    Hey guys, do you know that + 4 = ?

  • @liquidboy,

    >>>>>>> How does all this work when you use Expression Web to edit some of your HTML.

    We tried to pick a syntax that tools would be able to easily parse/support. Since it is a code-focused templating approach you won't necessarily get full WYSIWYG markup designer support - but tools like Expression will be able to still edit and work with the template. With CSS now being the primary way people customize their HTML, this works well - since it is the CSS design-time you really want designers customizing and that isn't impacted by this.

    Hope this helps,

    Scott

  • Nice, but I wonder if there is anybody within Microsoft still working on something innovating for Webforms.

  • @Anil,

    >>>>>>>>>> RAZOR sounds good. How about MVC-specific server controls that are totally unbound from the postback and view-state ????

    The Grid helper I used towards the end of the post is an example of the types of encapsulated scenarios we are looking to enable more in MVC. These types of helpers end up being really easy for people to build - and provide a lot of the productivity of server controls. They also fit in well with a MVC style model of development. You'll see us ship more helpers like that in the future.

    Hope this helps,

    Scott

  • @Asif,

    >>>>>>>>> Its a sad day for us WebForms developers that such a thing wont exist there or so I think because you havent talked about that in the post atleast,so how can we use it in Web Forms?

    You'll be able to use .cshtml/.vbhtml files within web forms based applications as well. Stay tuned.

    Hope this helps,

    Scott

  • This reminds me of coldfusion..where you mix all CF script with HTML.. and for a complex page, you end up with a spaghetti code. Maybe not only coldfusion, but classic asp as well. I really wish ASP NET don't go that way.

  • @Chris,

    >>>>>>>>> 1) Can these be precompiled or embedded into the assembly as a resource?

    Yes - that is one of the things we are looking to enable that I didn't mention in the post. We plan to enable you to add these to class library projects and compile them into assemblies.

    >>>>>>>>> 2) I didn't see anywhere that the 'Model' was specified, How will arguments be passed to views? Along that same vein, can we extend / override the base type for views? A method similar to spark's would be great.

    Yes - you can do both of these things. You can write:

    @inherits MyClass

    at the top of the view and have the view inherit from that. You could use this approach to specify a strongly typed model like you do today with MVC. For example:

    @inherits ViewEngine

    We are also considering just having a shorter way to-do this as well like so:

    @model MyModelType

    Hope this helps,

    Scott

  • @Quooston,

    >>>>>>>>> Not having to close every tag and replacing that concern with simple indentation is just awesome. All that brackety stuff is just so noisy ;)

    That isn't something we are currently planning to build-in support for with the first Razor release - but there is enough extensibility in Razor that you might be able to build your own extension to do it yourself.

    One reason we are adding the Add->View dialog with viewengine selection is because we realize that there will never be "one true syntax" that is perfect for everyone. Razor isn't designed to replace .ASPX, Spark or NHaml - there are good reasons to use other alternatives depending on your preference and workflow. We want to make sure you have the flexibility to use whichever feels most natural to you.

    Hope this helps,

    Scott

  • @Steve,

    >>>>>>>> Thanks Scott - I used NVelocity for 'mail merge' type functionality - I'm glad this was done so it can be independent of asp.net - this way, it will be a great template engine for all C# needs.

    Razor can be hosted outside of ASP.NET - so mail-merge like scenarios are definitely something that can be enabled with it.

    Hope this helps,

    Scott

  • @unsprung,

    >>>>>>>> I don't know if it could ever tear me away from Spark, but it's a start. Razor is more code-like than Spark, so it's easier than Spark to see where your code starts and ends without being as ugly as Webforms. Spark still wins for elegance though ;)

    One reason we are adding the Add->View dialog with viewengine selection is because we realize that there will never be "one true syntax" that is perfect for everyone. Razor isn't designed to replace Spark or NHaml or .ASPX - there are good reasons to use other alternatives depending on your preference and workflow. Some people prefer a more declarative syntax, some prefer a more code focused one. We want to make sure you have the flexibility to use whichever feels most natural to you.

    Hope this helps,

    Scott

  • @Chris,

    >>>>>>>>> Question - will there be any sort of support for dynamic compilation of the template pages? For example, take a CMS web app, the users of the app are allowed to edit these templates, store them in a DB as text, and then the app needs to compile and use them on demand.

    Yes - you'll be able to compile templates on the fly. Supporting this for CMS style scenarios is definitely something we are planning to-do.

    Hope this helps,

    Scott

  • @gringouc,

    >>>>>>> You're using in the first code sample the following code:

    /products/details/@productID instead of Html.ActionLInk or Url.Action.

    Generally I'd recommend using Html.ActionLink or Url.Action for scenarios where you are doing action links. For that particular example in the post I just wanted to keep it simple so that people who aren't familiar with those helpers could understand it.

    Note that the example I showed is useful for both action links as well as any generic URL on the web (where Html.ActionLink wpuldn't be appropriate).

    Hope this helps,

    Scott

  • I hope this drives the last nail to the XSLT coffin, not to mention asp.net forms crap

  • @Joshua,

    >>>>>>> How do you declare a strongly typed viewmodel?

    You can declare a strongly typed viewmodel by adding a statement like:

    @inherits MyViewClass

    We are also considering adding support in the future to just say

    @model MyModelType

    Note that the view base class is fairly decoupled from the syntax. You can swap in different base classes pretty easily - allowing the razor syntax to be used for a lot of different scenarios (for example: you could have a MVC base class, an inline page base class with different helpers, a mail-merge base class, etc). This is quite different than the .aspx parser today which assumes the Page base class.

    >>>>>>>>>> When is the view compiled - at build time, or runtime? Specifically, is there a backing type (like WebForms codebehind) that is discoverable at app startup time, or is the type compiled on the fly (like an aspx template)?

    By default razor files on disk are compiled at runtime (on demand). We've designed the syntax, though, such that you can also compile them explicitly at build-time. We are also looking to enable scenarios where you can add .cshtml files to class library projects and compile them into actual assemblies as well which you could then redistribute and/or reference from multiple projects.

    Hope this helps,

    Scott

  • This is great info thanks

  • re: inheritance

    Scott, please consider providing a way to specify a base type like MyViewBase at the application level, would really like to not have to @inherit on every page... i suspect that would cause too much pain on the intellisense providing side?

  • Yes, but does it support code?


    @if(DateTime.Now.Year == 2010) {
    Hello World! Check out @Razor
    }

  • Hi Scott, looks really cool. Will Razor be compatible with exiting helper classes like the MVC Contrib / Telerik MVC, or will they need to add code to enable the functionality you show in your Grid helper example?

  • Wow - IIS Express, SQL Compact 4 and now Razor? Evidently Christmas now comes in July. Extremely cool.

    On the random question front: it looks like C# and VB parsing is pretty deeply baked into Razor. Are there language extensibility hooks of some sort such that one register .fshtml files with F# support?

  • How about a proper hat-tip to the templating and view engines that 'inspired' the 'smarts' in Razor.

  • Scott, As far as I know you can also use @: instead of tags.

  • What about doing something completely crazy and say storing my View in a Database and not in a .cshtml file will this be possible?

    Also are you going to include support for say .rbhtml(IronRuby) files out of the box?

  • This is great. Glad to see Microsoft is making the leap towards conventions instead of heavy configuration.

  • @Attila,

    >>>>>>> @Scott, will you release it on CodePlex but at least with Source Code? That should be awesome!

    I'm pretty sure we'll be releasing the source code to it (note: we do that for all of ASP.NET MVC).

    Hope this helps,

    Scott

  • @Ryan,

    >>>>>>>> Will Razor remove unneeded whitespace and/or html comments at compile-time, preferably through a setting?

    That is an interesting idea - I don't think we support that right now, but it could be a nice feature to add.

    Hope this helps,

    Scott

  • @Alex,

    >>>>>>>>> One of the biggest complaints is the use of the "{ }" as well as "" syntax. I am not seeing much difference in this new syntax when compared to the old. It still ends up looking like spaghetti code, IMHO. How about something more like spark syntax? It mingles nicely with and into the HTML. And while on that subject, why not just endorse spark as an official view engine?

    Spark is great - which is why we are making it easy to integrate within the Add->View dialog. We didn't try to go the Spark approach with Razor mainly because Spark already existed (and so why duplicate it). For people who prefer a more declarative approach to view engines I'd recommend using Spark.

    A lot of people prefer a more code-focused approach (and want to use their native programming language as opposed to learning a new imperative grammer), which is one of the reasons why Razor took the approach it did. We want it to be a great offering for people who prefer that approach.

    Hope this helps,

    Scott

    P.S. Louis, who runs the Spark project, is actually on the ASP.NET team. So we do love it (and him) a lot! :-)

  • @Aaron,

    >>>>>>>>> (The jquery-tmpl stuff isn't moving as fast as I'd expected).

    We actually are making some good progress on the jQuery template and linking work. We'll post more details soon.

    Thanks,

    Scott

  • @Erwin,

    >>>>>>>>>> Nice, but I wonder if there is anybody within Microsoft still working on something innovating for Webforms.

    There definitely are. Lots of goodness still coming out with Webforms.

    Hope this helps,

    Scott

  • @Chris,

    >>>>>>>> Scott, please consider providing a way to specify a base type like MyViewBase at the application level, would really like to not have to @inherit on every page... i suspect that would cause too much pain on the intellisense providing side?

    Good suggestion - I'll pass it along to the team.

    Thanks,

    Scott

  • @Thomas,

    >>>>>>> Yes, but does it support code?

    >>>>>>>>

    >>>>>>>> @if(DateTime.Now.Year == 2010) {
    >>>>>>>> Hello World! Check out @Razor
    >>>>>>>>}

    >>>>>>>>

    Hmm - I'm not sure I understand your scenario. Can you provide more details?

    thanks,

    Scott

  • @Aaron,

    >>>>>>>>> Hi Scott, looks really cool. Will Razor be compatible with exiting helper classes like the MVC Contrib / Telerik MVC, or will they need to add code to enable the functionality you show in your Grid helper example?

    Yes - all existing HTML helpers (including those in MVC Contrib and Telerik) are fully compatible with Razor.

    Hope this helps,

    Scott

  • Scott, this looks very cool! It looks to be definite improvement over the WebForms engine with all its verboseness. A short question on Razor: will it support the existing caching features?

  • @Blake,

    >>>>>>>>> On the random question front: it looks like C# and VB parsing is pretty deeply baked into Razor. Are there language extensibility hooks of some sort such that one register .fshtml files with F# support?

    Razor itself can support multiple languages (it isn't just baked in for C# and VB). So adding F# support is possible.

    Hope this helps,

    Scott

  • @VAI,

    >>>>>>>>> What about intellisese in html attributes? Today .aspx intellisense didn't work when I'm typing something like this: <tr class="">..., but this works and my feel is that intellisense isn't complete with this.

    The good news is that the VS editor for Razor will handle this just fine. You'll get intellisense completion of code within attributes.

    Hope this helps,

    Scott

  • Great to see a new view engine. I presume the intellisense extends to the HTML... but is there a way to specify my own schema and still get intellisense? So I could create a razor page to generate XML against my own schema? It would be great if that was available and warnings were generated by the compiler when the schema was not adhered to... Not much to ask ;-)

    Piers

  • @Chris W

    >>>>>Question - will there be any sort of support for dynamic compilation of the template pages? For example, take a CMS web app, the users of the app are allowed to edit these templates, store them in a DB as text, and then the app needs to compile and use them on demand. This is something I can't seem to do now in regular ASP.NET.

    You can actually do this today for both WebForms and the WebForm view engine in MVC (and Razor :-D) by implementing a virtual path provider.

  • @ScottGu:

    It looks really good. I'm very excited about it and can't wait to get my hands on it. If I can give you any advice, please keep the focus 100% code/HTML-focused and leave the designer, drag-n-drop stuff for ASP.NET WebForms. I think then everyone will be happy!

  • Would Razor enable support for an output caching mecanism more appropriate with ASP.Net MVC ?
    Something REALLY nice would be an output cache based on action parameters, and usable with RenderAction

  • Razor seems like it would be PERFECT for implementing a CMS if it can be compiled at run time. Does this also mean a user of such a 'Razor powered' CMS could replace a masterpage or other templates during runtime, without an app restart? Hopefully the answer is yes as you'd hate to destroy all the user sessions because of a content change. In my opinion, such on the fly template compilation would make asp.net immensely more powerful. Got my fingers crossed!

  • wow! This is great thing! Can't wait to start testing it...

  • Hey Scott,

    I'm pleased to see MS working at an alternative to .aspx. However, in my opinion you guys are being much too conservative with Razor. Sure, its definitely simpler and lighter than .aspx, but in my opinion its still much harder to look at compared to spark or nhaml. At least with what I see in this post, Razor seems to be a pretty incremental improvement to .aspx when I was hoping for something much more ambitious. I agree with Alec above that the way the code mingles with the HTML is key, and Razor still leaves much to be desired in that area. On the bright side, I really appreciate that you have made MS MVC very extensible and so it is easy to embrace the frameworks from the community that are really pushing the envelope (such as spark and haml).

  • 1) Razor looks pretty slick (concise and expressive).
    If it would be really testable -- I might finally start switching to MVC.
    2) I agree with Chad Myers -- no need for drag&drop designers for ASP.NET MVC / Razor -- code only please.

  • Why not just adopt NHaml and ship it with asp.net much the same way you did with jQuery? Why re-invent the wheel? BTW, WebForms are a parasite on the web. ViewState abuse, monolithic forms, terrible markup, etc. MS should begin the deprecation of WebForms in favor of MVC. For once, do the web some good.

  • Why stop here? make this the "xml literal" support in C#. Mixing code and markup is not a requirement exclusive to ASP.NET

  • This looks amazing, Scott! I've been diving into ASP.NET MVC lately, and have always been a bit nagged by the inelegance of the Web Forms view engine. And then this comes along!

    Two questions:

    1) If I want to split up my statement and my opening brace { on two lines, can I do that? None of your examples do, and I can see where it might not be as straightforward to parse. But one could kind of expect this to work, from a C# developer standpoint.

    2) PLEASE consider adding support for .csjs (and .vsjs) files, so we can intermix code into our JavaScript! I can definitely appreciate that this (and, I suppose, counterpart .cscss and .vbcss support) might be a "we'll consider this for next release" feature, but it would definitely get rid of a lot of the hacky work-arounds that we see today, and seems to fit in well with what you're already doing.

    Thanks for the recent posts, Scott :D. The only downside is that these cool things you keep showing us aren't immediately available; they're so awesome that I want to play with them right away!

  • Oh I see, for the

    @if(DateTime.Now.Year == 2010) {
    }


    You would just escape the @@ appropriately. I was thinking if you placed anything in the block that Razor would understand that you don't want to interpret, but it sounds like all you need to do is escape @.

    Nevermind :)

  • It seems interesting. Going to try hands on it.
    thanks for building this gr8 view engine for ASP.net MVC.

  • The tag seems a little clunky, especially since this is moving towards a more code-oriented approach. Having to sometimes inject "fake" tags and sometimes not depending on the content seems a little inconsistent/confusing. It would be great if there was a way to avoid that.

  • Thanks Scott!

    I hope that also the Visual Studio tooling part will be released in source code form as well, so the community can have a full blown editor, intellisense, etc. code written for VS2010!

    I know MVC, I wrote the MVC chapter in the upcoming Visual Studio 2010 6 in 1 by Wiley :-)

  • Looks very nice, but I was wondering how would you handle globalization/localization. Your example included markup like $@p.Price and @DateTime.Now. How would you display these native types as currency and dates in local cultures?

    Also, I really do hope you go with the @model MyModelType syntax for specifying view models.

  • very nice, much better (less verbose) than asp.net view engine or spark..
    much like nvelocity

  • Wow, this is a great example of innovation within Microsoft and thinking outside of the box! Well done team

  • Hi Scott,

    This looks incredible, can't wait for the first beta/ CTP.

    I noticed a few people are asking, but unanswered as yet, so I thought I'd ask as well...

    Will there be the facility to load Razor files from places other than the drive? - I.e. a database/ WCF Endpoint...?

    Thanks,
    Kieron

  • That looks sweet! Looking forward to trying the beta!

  • What is the view engine lifecycle like? I'm assuming the whole ASP.NET lifecycle will go away with Razor?

    If so, how will dynamic registration of css and javascript be handled in Razor? Something like a in ASP.NET where components can add css and javascript before the page is rendered.

    For example, how would your grid component add it's javascript to the page, and add it only once?

  • @ScottGu - I do understand where you are coming from, maybe we could find a happy medium and have as Rob E. suggested, code statements in the HTML such has how Spark does Each and If.

    This has been a big week for you guys - looking forward to seeing IIS Express.

  • I love the "@" idea. Makes things very easy. Was it inspired by Twitter?

  • what about Nested LayoutPages?

  • What the h3ll is so great about MVC?? This crap looks like old-classic ASP to me. What about all the talk of the benefit of separating the HTML from the code? Still not seeing the beauty, sorry.

  • Take a vacation day already.

  • Will razor somehow work around the "hacky" donut and donut whole caching that is involved with ASP.NET currently?

  • This sounds like a useful engine! Does it support dynamic data scaffolding (or an equivalent abstraction)?

  • Why masterpages and helpers, why not just function calls?

    @masterpagename1(arguments,

    @helpername(arguments,

    )

    )

    @functioncall1(arguments,
    @functioncall2(arguments,

    @functioncall3(arguments,

    )

    )
    )

  • great..wait for the day when it will be released

  • Sadly, the @ key is not easy to type using a french layout keyboard. It will require two hands, once for the alt-car (right alt) and the other for the 2 key.

    But I still have to say that this is better that the usual construct.

  • Scott,

    nice to help us,
    a helper to create css tables layout
    boxed css
    i love how easy we can layout on silverlight

    and about razor,
    partial update ? partial cache ? donut cache ? client cache ?

  • To me this looks to be like an expression bases syntax like Classic ASP and somewhat like PHP. I thought the whole concept behind shifting to ASP .net Code behind model was avoiding Spaghetti coding style (separating markup from functional code).

    And this looks to be a step back rather than being a step forward. I am simply confused by the direction of this.

    Regards,
    Junaid Mufti

  • Well I'm starting to love MVC. But still it is for me like a kind of spaguetti code. Maybe I haven't seen the real advantage of those View Engines. What you could recommend me to understand more the difference?

  • When do you expect it to be released?

    Thanks!
    :)

  • That's really cool stuff!
    Hope that this new view engine can working on Mono too.

  • Will there be Intellisense-Support vor Visual Studio 2008???

  • It's really more shortener and more readable. Good "contentplaceholder" implementation as short RenderSection(...) record

  • I'm still interested in the logic behind starting a new view engine from scratch rather than lending support to Spark or NHaml?

    I'm a massive fan of Spark, but it's currently not the easiest to use due to lack of integration with the VS2010 IDE - no intellisense, syntax highlighting, etc. As a result, the learning curve is much steeper than it needs to be. People are working on it, but it's in their own time and as a result it's progressing slowly. It strikes me that MS could have done a huge amount to help "productionize" Spark with relatively little effort, at massive benefit to the ASP.NET MVC community.

    Instead, you've taken the decision to start a new view engine from scratch. Whilst I applaud the moves to make it easier to substitute view engines in the framework and tooling - and hopefully to move people away from the WebForms view engine by default - I'd love to know why starting afresh was the right direction for the team to take?

    Thanks
    Jon

  • I am moving slowly to MVC, but things you do with it make me wanna use it on everyday basis. Needless to say, while learning MVC I had urgent need to see origins of it - so I started to look into Ruby on Rails and know I have much cleaner picture of great job you guys are doing.
    You have my endless support - just keep going with MVC...

    Cheers

  • Thanks for it, it looks very nice and I wanna use it right now :)

    But my question is: Is there any limitations comparing to standard aspx-view? Is there any known issues?

    Thank you.

  • Waiting for the Beta release soon!

  • Great another thing to learn, another thing to maintain

  • Hi Scott,

    nice one.

    Is it possible to use it from VS.NET 2008?

    Thanks.

  • but put statement: @if(DateTime.Now.Year == 2010) in the view is not good practice in MVC paradigm or not?

  • This looks like a great improvement on the standards .aspx view engine. Will it have support for dynmically swapping the view or theming?

  • What about support for bi-directional binding?

  • I already have lot of .aspx, .ascx views in my ASP.NET MVC project, will I be able to use both webform view and razor views at the same time in one app? So for my future views I'll use razor but for my existing views let them stay where they are?

    Thanks
    Ray.

  • Any plans to incorporate this technology into "the next" T4+ template engine?

    Regards, Robert

  • Can't wait to use this code. A brilliant improvement.

  • This looks exciting.

    Congratulations for injecting a spark into the stagnant world of markup.

    I remember years ago being able to use JScript, VBScript, Perl... to do back end and to somewhat do front end coding. It was a great start, plug in your scripting language and go.

    Then along came .NET. I really love it in many ways. Like it sorted out the major problems with Web Classes, and it does that astonishingly well! It has ASHX's! But it has issues like:

    1) Those control names that get injected and make controls not worth using if you want clean browser side coding that you actually control.

    2) Master pages, see controls above.

    3) No common execution environment with original ASP.

    4) Testing is doable but it's really hard work.

    5) If you know HTML, CSS and Browser side scripting a lot of the design decisions are a kick in the teeth. An assumption that you don't know any of this stuff and a tool to enforce ignorance on those who start off not knowing.

    The MVC idea (horrible name!) has always looked promising but has had it's issues too.

    Now if I read this right, and my hopes are fulfilled, I can mix ASPX, Razor... pages. One execution environment. Compiled bits, bits which get compiled on demand, some functionality in a web service, maybe my code generates some of the pages on the fly... Pages without extensions, some with. Deploy small changes quickly, touching nothing else, if I want.

    If it's all those things that early promise and excitement might just fire our minds up again.

    I'd love to see:

    A) Mix my languages and worry less about separately compiled assemblies. Not sure the granularity there, one possibility is a page in C#, one in VB.NET and another in F#, compiler framework does the work of weaving them together!

    B) I still have a few "legacy" things running in the original ASP (they're not going to change that I can see, no budget cause they just work!). It's a bit of gymnastics to blend those with ASP.NET. A lot of people seem to go for interpreted, scripting on the server. I reckon merging good old traditional ASP, into the ASP.NET execution environment would kinda complete the circle. It would get back some of that brave new world when the web was a younger and a more hopeful place! Heck done right it would provide a path for all those PHP programmers to extend their capabilities.

    Great potential. Thanks. I hope the promise of greater things comes to pass.

  • This is great and the ASP.NET team is really rocking

  • You made an excelent job Scot, Love u!

  • Thanks Scott, great article. I do have 2 questions though;

    1) When can we expect to see the beta?
    2) This is probably a more sensitive one, why? Why a new view engine? I mean I can see the new cool features, but why not take something like Spark and throw resources at that and get that going with intellisense and syntax highlighting.

    I am not complaining, but I really fail to see the rationale behind this new view engine.

  • Looking good, Scott. I wonder if "Razor" will implement some of the foreach features seen in NVelocity, such as #between, #odd, #even, #nodata, etc.

  • I can't wait to try this to see if it makes the views as clean as I think it will. I find the syntax quite noisy on the page and Razor looks to quieted this all down a lot. Well done to you and your team!

  • Scott,

    I am the next one who calls for fair play with Spark and NHaml, and maybe NVelocity. These projects are not competitors to MS. And it will be good if their leaders spend part of time to proceed the development.

  • Scott, seems really cool to me. Thanks for sharing such wonderful article and keep sharing like this.

  • This looks great! I would definitely like to see this as the default view engine for the next MVC release!

  • Great news Scott and team! Please, keep this kind of innovation up. Do NOT let the nah-sayers stifle your efforts; they are usually just restricted by their tunnel vision.

    Will there be a way to provide default section content in a layout page that defines an optional section? For example:

    ...
    @RenderSection("title", optional:true, defaultContent:"Sample Site")
    ...

    OR

    ...

    @RenderSection("quote", optional:true, defaultTemplate:"RandomQuote.cshtml")

    ...

  • This is very nice!

    But there are three things that are more important than saving the key strokes:
    1) provide intelligent support of design time view. The design time view is much more vivid than just reading all html codes
    2) Make syntax more natural. I feel I don't like the syntax of columns in @Grid.Render. Could you make it more fluid? like column=>"Name", "Product", style:"product".
    3) Could ASP.NET team provide auto generation of common html/css templates? like menu, tab, tree, repeater, grid, and even some application template such as generic CRUD for a single table? As such, developing applicaitons with ASP.NET MVC will be much faster!

  • Great News! For me it seems like those views will be much more convinient than ASP.NET web forms, especially when IntelliSence will fully support them.

  • Hi Scott,

    Razor looks really nice to work with but... for users to take up on this new approach I think we need to get a good understanding of where Razor fits in the whole ASP.NET vs ASP.NET MVC 2 debate. With this I mean that for Razor to become a mainstream view engine it must have a solid place on the road map of the development of ASP.NET MVC.

    Personally I don't like the it smells too much of classic ASP and I would rather see Razor to become the leading approach to ASP.NET MVC but before I make a commitment to the frenzy I want to know what the commitment is from Microsoft in regards to the (marketing/learning/guides/tools/books/etc) support for future development.

  • Looks like a few of us see more than a passing similarity to classic ASP and are worried about the separation of concerns for markup and code. Do you have any comment on that? Isn't this a step backwards? Why or why not?

  • I feel a bit sorry for the Spark and NHaml guys.

    I was just reading about Spark earlier today, when I got a link to this post and decided against it.

  • I am developing ASP.NET from day one. If you look at other devisions at Microsoft that are responsilbe for WPF/Silverlight or even legacy Frameworks like Windows Forms, those people always did one amazing thing: Putting very complex stuff on a very high abstract level. The current ASP.NET team doesn't seem to have those skills.

    If i am looking at things like ASP.NET MVC i am highly skeptical and dislike the way ASP.NET is moving. One of the biggest reasons for introduction of ASP.NET webforms was separation of code and markup. Instead, it looks like the they are following some very dogmatic ways by strictly implementing patterns.

    Developing like in old days, just with a bit oo backup can't be really the road to go!

  • Please don't ask why, but is the standard syntax for rendering 'WebControls' such as still possible while using a Razor view? I know what you guys are thinking, but I just need to know if this is possible.

    Thanks!

  • @RenderSection("menu", optional:true) - How about making "optional" parameter be true by default!

  • Sounds good
    Needs more to yet awaited

  • This looks amazing! I'm definitely using it on the product I'm building right now with ASP.NET MVC

  • I am all excited about this!. Hope to try it out when its released.

  • This looks awesome, and the declarative HTML helper syntax is a great idea. I really like the fact that you can use several view engines within the same project. The problem will be when using master/layout pages, you would need a version for both view engines. Although I guess this can be solved by creating Helper methods and call them in both the master and the layout page. Great job guys!

  • A little bit late on catching up on the Razor party.

    Lovely work!

  • Could you cover Spark engine integration with IDE?
    Also code-centric template is fine. But it might be too free to be abused like code-behind.
    It will be great if MVC template engine can follow "MVVM", presentation model approach making UI really dumb so that it only deasl with binding and event delegation.

    For example Spark engine defintely more restrictve. It is really hard to abuse it to mingle UI and business logics so often.

  • yay...

    It's VB Classic all over again. Congrats on re-inventing the wheel.

    Now the real coders of the world will have to endure 2+ years of script monkeys who can't code doing all the good project for too cheap. Then the customers will fire their stupid asses and call up us real programmers to fix all the crap they leave behind.

    I'm not happy about this.

  • I am not quite sure I understand what "Razor" is supposed to accomplish. After spending nearly 10 years being indoctrinated to not mix code with the front-end (which actually makes a lot of sense) we now instead see more and more of this nonsense encouraging developers to do just the opposite.

    "Classic ASP" was constantly derided as difficult to maintain because of the combining of two code-bases; either it was described as spaghetti-code (because it was in many cases) or simply a poor paradigm (that is questionable dependent on how ASP pages were coded).

    Now by creating a new implementation of the original we are now told that this is a completely new paradigm because it is also linked with MVC. I have a lot of respect for Scott's work but this is just utter nonsense.

    I would not be surprised if this recent addition to the ASP.NET coding techniques is being fostered by the sustaining popularity of PHP and nothing else.

    I'm sticking with the code-behind model which works just fine the way it was designed...

  • very nice, love it

  • @Black Falcon

    Mixing code and markup if fine as long as you follow the separation of concerns pattern.

  • I'm utterly dumbfounded. This is EXACTLY what I've been wanting. Spark is decent view engine but lacks the level of support our organization requires. Razor obviously has the support backing and a whole lot more bells and whistles that will make things easier (and more readable). I'm downloading the beta has soon as possible. With any luck, we, as an organization, can make the leap to MVC and fully realize the power of unit testing upper level "ui code".

    Can't wait,
    Kevin

  • Ummm.... I'm VERY confused here. Why are people praising a concept that basically is old PHP smarty or ASP classic? This looks at BEST like every php framework for the last 5-6 years or at worst, just plain "Spaghetti code"!

    Where are the webforms? Isn't the encapsulation of controls and the seperation of presentation and logic the whole point of .NET??? WTF?! Now you're just throwing logic back into the presentation, where it's been since the start of web development? For loops for lists & tables instead of DataSource/DataBind using a recordset approach? What in god name are you people thinking? So many people praising a backwards step? Sorry, I'm truly baffled.

  • lovely view engine

  • I think that this RAZOR stuff is completly crap. The M$ again doing the same thing all over again. 10 years doing separation between html and code, and now this RAZOR is a good thing?!
    I hope for the sake of a new C# programers that you will abandon this and continue to teach them a proper way of doing things.

  • Will Razor still create a Control Tree before rendering just like Web Forms View Engine?

  • at last we so need this, good work.

  • Can you prevent it from adding extra line breaks? e.g. it should render:

    This is my custom footer for Home

  • I really like it. A big step in the right direction. That said (and not to sound like a whiner) you mention that Lou works for you, does that mean he will continue to work on Spark with MS's blessing. I am really impressed with the Spark Engine but don't want to be left with a dead end. The Spark Engine doesn't appear to be a very active site lately.

  • This is way cool, complete control of HTML layout and rendering + extras, Im so in.

  • @BlackFalcon i totally agree with you.... what exactly is this new direction? an inspiration from open source?
    wasn't the code behind approach was pushed by Microsoft... and we all just loved it, easy to maintain and easy to code...
    than why this Razor tech?

  • @Piers,

    >>>>>>>> Great to see a new view engine. I presume the intellisense extends to the HTML... but is there a way to specify my own schema and still get intellisense? So I could create a razor page to generate XML against my own schema? It would be great if that was available and warnings were generated by the compiler when the schema was not adhered to... Not much to ask ;-)

    I believe that will work - but am not 100% sure. I believe our HTML intellisense is still schema driven - so you could create your own and get intellisnse for it within a razor file.

    Hope this helps,

    Scott

  • @Guillaume

    >>>>>>>>>> Would Razor enable support for an output caching mecanism more appropriate with ASP.Net MVC ? Something REALLY nice would be an output cache based on action parameters, and usable with RenderAction

    Yes - this is something we are looking to enable in the future, both for Razor and the .ASPX view engine.

    Hope this helps,

    Scott

  • @Chris,

    >>>>>>>> Razor seems like it would be PERFECT for implementing a CMS if it can be compiled at run time. Does this also mean a user of such a 'Razor powered' CMS could replace a masterpage or other templates during runtime, without an app restart? Hopefully the answer is yes as you'd hate to destroy all the user sessions because of a content change. In my opinion, such on the fly template compilation would make asp.net immensely more powerful. Got my fingers crossed!

    You are going to see us using Razor within our "Orchard" project - which is an open-source ASP.NET MVC CMS system.

    Hope this helps,

    Scott

  • @Salman,

    >>>>>>>> Scott, would it be possible to have the templates user editable and safe/secure in that respect? i.e. the templated code should only output what was injected into it (Strongly typed View Data) and nothing else?

    Conceptually if you were using Razor within a CMS-like environment you could do this. By default Razor doesn't explicitly provide it - but you could layer it on top of it.

    Hope this helps,

    Scott

  • @Domenic,

    >>>>>> 1) If I want to split up my statement and my opening brace { on two lines, can I do that? None of your examples do, and I can see where it might not be as straightforward to parse. But one could kind of expect this to work, from a C# developer standpoint.

    Yes - you can have the braces be on separate lines (I just tested that and it works fine )

    >>>>>>>> 2) PLEASE consider adding support for .csjs (and .vsjs) files, so we can intermix code into our JavaScript! I can definitely appreciate that this (and, I suppose, counterpart .cscss and .vbcss support) might be a "we'll consider this for next release" feature, but it would definitely get rid of a lot of the hacky work-arounds that we see today, and seems to fit in well with what you're already doing.

    It is something we can look at.

    >>>>>>>>> Thanks for the recent posts, Scott :D. The only downside is that these cool things you keep showing us aren't immediately available; they're so awesome that I want to play with them right away!

    You can download Razor now as part of WebMatrix. We'll have a ASP.NET MVC release coming out shortly with it too.

    Enjoy!

    Scott

  • @Shawn,

    >>>>>>>>> The tag seems a little clunky, especially since this is moving towards a more code-oriented approach. Having to sometimes inject "fake" tags and sometimes not depending on the content seems a little inconsistent/confusing. It would be great if there was a way to avoid that.

    An alternative to using is to use the @: sequence - this will escape out to text as well and is a little terser.

    Hope this helps,

    Scott

  • @Michael,

    >>>>>>>>> Looks very nice, but I was wondering how would you handle globalization/localization. Your example included markup like $@p.Price and @DateTime.Now. How would you display these native types as currency and dates in local cultures?

    By default we will format the values using the globalization/localization settings for the request (which an app can either hard-code or dynamically change based on the user's preferences). All of the existing .NET globalization/localization logic works the same.

    Hope this helps,

    Scott

  • @Kieron,

    >>>>>>>> Will there be the facility to load Razor files from places other than the drive? - I.e. a database/ WCF Endpoint...?

    Yes - you should be able to load them from anywhere.

    Hope this helps,

    Scott

  • @Chris,

    >>>>>>>> What is the view engine lifecycle like? I'm assuming the whole ASP.NET lifecycle will go away with Razor? If so, how will dynamic registration of css and javascript be handled in Razor? Something like a in ASP.NET where components can add css and javascript before the page is rendered. For example, how would your grid component add it's javascript to the page, and add it only once?

    The page-lifecycle is not supported with Razor. For resources like JavaScript one of the things we'll be using is an approach called "unobtrusive Javascript" where instead of injecting JavaScript within the page you instead take advantage of external Javascript files and have helpers like the Grid take advantage of them that way.

    Hope this helps,

    Scott

  • @Kim,

    >>>>>>>>> what about Nested LayoutPages?

    Yes - nested layoutpages are fully supported!

    Thanks,

    Scott

  • @Stephen,

    >>>>>>>>> This sounds like a useful engine! Does it support dynamic data scaffolding (or an equivalent abstraction)?

    Razor itself is more just the syntax/view engine - but we do have helpers (with MVC 2) that support dynamic data scaffolding and they'll work with it.

    Hope this helps,

    Scott

  • @Junaid,

    >>>>>>>> To me this looks to be like an expression bases syntax like Classic ASP and somewhat like PHP. I thought the whole concept behind shifting to ASP .net Code behind model was avoiding Spaghetti coding style (separating markup from functional code). And this looks to be a step back rather than being a step forward. I am simply confused by the direction of this.

    Some people like a controls model with code-behind for code/content separation, and others like a MVC model where there is separation between the controller and view. In an MVC model your application/business logic is contained within the controller and model layers - and does not live in your view. Your view file instead just focuses on generating HTML rendering.

    Both WebForms and MVC are fine models, and we want to make sure we have great support in ASP.NET for both. You don't need to use MVC unless you want to.

    Hope this helps,

    Scott

  • @David Taylor,

    Good suggestions - I'll pass them along to the team!

    Thanks,

    Scott

  • @dacanetdev,

    >>>>>>>>> Well I'm starting to love MVC. But still it is for me like a kind of spaguetti code. Maybe I haven't seen the real advantage of those View Engines. What you could recommend me to understand more the difference?

    Some people like a controls model with code-behind for code/content separation, and others like a MVC model where there is separation between the controller and view. In an MVC model your application/business logic is contained within the controller and model layers - and does not live in your view. Your view file instead just focuses on generating HTML rendering.

    Both WebForms and MVC are fine models, and we want to make sure we have great support in ASP.NET for both. &nbsp;You don't need to use MVC unless you want to.

    Hope this helps,

    Scott

  • @Jonathan,

    >>>>>>>>>I'm still interested in the logic behind starting a new view engine from scratch rather than lending support to Spark or NHaml? I'm a massive fan of Spark, but it's currently not the easiest to use due to lack of integration with the VS2010 IDE - no intellisense, syntax highlighting, etc. As a result, the learning curve is much steeper than it needs to be. People are working on it, but it's in their own time and as a result it's progressing slowly. It strikes me that MS could have done a huge amount to help "productionize" Spark with relatively little effort, at massive benefit to the ASP.NET MVC community.

    >>>>>>>>>> Instead, you've taken the decision to start a new view engine from scratch. Whilst I applaud the moves to make it easier to substitute view engines in the framework and tooling - and hopefully to move people away from the WebForms view engine by default - I'd love to know why starting afresh was the right direction for the team to take?

    We love Spark - which is one of the reasons we've updated the "Add View" dialog to be extensible so that any view engine can more easily plug into VS. We expect many developers to use it instead of Razor in the future.

    We created Razor partly because we wanted to have an option where developers could re-use the languages they already knew (C#/VB/Whatever) and not have to learn a new imperative language purely for templating. One challenge with declarative templating languages is that you have to effectively learn a new syntax for doing things - and the tools (intellisense, refactoring, debugging, profiling) also all have to be written from scratch to support it. As traditional languages have gotten richer (C# and VB with .NET 4, and other dynamic languages) the expressiveness that you can achieve with existing imperative languages has also gotten a lot richer. We wanted to be able to leverage all that within our view templates - which is why we introduced Razor as an option.

    Hope this helps,

    Scott

  • @Artem,

    >>>>>>>> One of the most significant things in Spark view engine is that layout templates are rendered AFTER main templates. It allows specific page to register something to deal with afterwards in layout. For example whereslou.com/.../very-cool-use-of-macro-and-_globalspark I'd be thrilled if this approach was adopted by Razor. Is it so?

    Yes - this is also supported by Razor.

    Hope this helps,

    Scott

  • @Dmitryii,

    >>>>>>>> One of the most frustrating things working with views in ASP.NET MVC is passing the values from a controller to a view. So the syntax that would read values from ViewData dictionary would the biggest time saver. Something along this:

    >>>>>>>> @currentTime.ToString("d")

    >>>>>>>> which would be equivalent for

    >>>>>>>>> .

    >>>>>>>>> So that we do not even need to provide the time of the object in the ViewData.

    This is something we are looking to enable with Razor integration with ASP.NET MVC. You'll be able to write the below to reference a property from ViewData:

    The time is: @View.CurrentTime


    Hope this helps,

    Scott

  • @Ray,

    >>>>>>>>> I already have lot of .aspx, .ascx views in my ASP.NET MVC project, will I be able to use both webform view and razor views at the same time in one app? So for my future views I'll use razor but for my existing views let them stay where they are?

    Yes - you can absolutely use both .aspx/.ascx and razor views in the same ASP.NET MVC project.

    Hope this helps,

    Scott

  • @rn,

    >>>>>>>> 2) This is probably a more sensitive one, why? Why a new view engine? I mean I can see the new cool features, but why not take something like Spark and throw resources at that and get that going with intellisense and syntax highlighting.

    We love Spark - which is one of the reasons we've updated the "Add View" dialog to be extensible so that any view engine can more easily plug into VS. We expect many developers to use it instead of Razor in the future.

    We created Razor partly because we wanted to have an option where developers could re-use the languages they already knew (C#/VB/Whatever) and not have to learn a new imperative language purely for templating. One challenge with declarative templating languages is that you have to effectively learn a new syntax for doing things - and the tools (intellisense, refactoring, debugging, profiling) also all have to be written from scratch to support it. As traditional languages have gotten richer (C# and VB with .NET 4, and other dynamic languages) the expressiveness that you can achieve with existing imperative languages has also gotten a lot richer. We wanted to be able to leverage all that within our view templates - which is why we introduced Razor as an option.

    Hope this helps,

    Scott

  • @ventaur

    >>>>>>>>> Will there be a way to provide default section content in a layout page that defines an optional section?

    Yes - this is supported :-)

    Thanks,

    Scott

  • @developer,

    >>>>>>>> If i am looking at things like ASP.NET MVC i am highly skeptical and dislike the way ASP.NET is moving. One of the biggest reasons for introduction of ASP.NET webforms was separation of code and markup. Instead, it looks like the they are following some very dogmatic ways by strictly implementing patterns.

    Some people like a controls model with code-behind for code/content separation, and others like a MVC model where there is separation between the controller and view. In an MVC model your application/business logic is contained within the controller and model layers - and does not live in your view. Your view file instead just focuses on generating HTML rendering.

    Both WebForms and MVC are fine models, and we want to make sure we have great support in ASP.NET for both. You don't need to use MVC unless you want to.

    Hope this helps,

    Scott

  • @Josh,

    >>>>>>>> Please don't ask why, but is the standard syntax for rendering 'WebControls' such as still possible while using a Razor view? I know what you guys are thinking, but I just need to know if this is possible.

    That isn't supported right now I'm afraid. Webcontrol markup is only supported within .aspx pages.

    Hope this helps,

    Scott

  • @Black Falcon,

    >>>>>>>>> "Classic ASP" was constantly derided as difficult to maintain because of the combining of two code-bases; either it was described as spaghetti-code (because it was in many cases) or simply a poor paradigm (that is questionable dependent on how ASP pages were coded).

    Now by creating a new implementation of the original we are now told that this is a completely new paradigm because it is also linked with MVC. I have a lot of respect for Scott's work but this is just utter nonsense. I would not be surprised if this recent addition to the ASP.NET coding techniques is being fostered by the sustaining popularity of PHP and nothing else. I'm sticking with the code-behind model which works just fine the way it was designed...

    Some people like a controls model with code-behind for code/content separation, and others like a MVC model where there is separation between the controller and view. In an MVC model your application/business logic is contained within the controller and model layers - and does not live in your view. Your view file instead just focuses on generating HTML rendering.

    Both WebForms and MVC are fine models, and we want to make sure we have great support in ASP.NET for both. &nbsp;You don't need to use MVC unless you want to.

    Hope this helps,

    Scott

  • @Gavin,

    >>>>>>>>> Where are the webforms? Isn't the encapsulation of controls and the seperation of presentation and logic the whole point of .NET??? WTF?! Now you're just throwing logic back into the presentation, where it's been since the start of web development? For loops for lists & tables instead of DataSource/DataBind using a recordset approach? What in god name are you people thinking? So many people praising a backwards step? Sorry, I'm truly baffled.

    Some people like a controls model with code-behind for code/content separation, and others like a MVC model where there is separation between the controller and view. In an MVC model your application/business logic is contained within the controller and model layers - and does not live in your view. Your view file instead just focuses on generating HTML rendering.

    Both WebForms and MVC are fine models, and we want to make sure we have great support in ASP.NET for both. You don't need to use MVC unless you want to. WebForms continues to get better and better with ASP.NET 4.

    Hope this helps,

    Scott

  • @Gavin.

    Haven't tried it myself yet, but there's articles about using ASPX and MVC side by side. Including some by people who're doing it in real life.

    Seems you can put MVC pages into an ASPX site and vice versa with little extra work.

    So you can have have your ASPX forms co-exist with MVC. Both under active development, both sharing session state etc. Sounds like a best of both worlds situation.

  • This looks like Classic ASP. I hope I'm wrong because that would be a step backwards.

  • Will it be possible to render a template in such a way that it only has access to the objects explicitly passed to it? Ability to render templates from DB (and other unusual sources) is an extremely powerful thing, but it's often frowned upon because of security concerns. Having some king of restricted rendering mode would help in that respect.

  • Simply Great. I have made a Hello World database application using Razor.

  • That's great that we have yet another template language to use and all. But I still prefer to create my html using C#. Which enables me to create flexible view modules that can be extended and since it is in C# has great intellisense. Currently I use a JQuery approach on the server side to write html and then write that to the page as a stream.
    Using templates feels like we are going back to classic asp. For one templates do not seem very extendible and second it seems we could very easily wind up with some of the nightmares that we had with classic asp. For instance the dreaded #include in a middle of a page.

    No longer are we just coding websites but web applications and using templates feels a step backward in the web app world.

  • First of all I want to say keep up the great work, I have been looking forward to something other then the Spark and Web Forms view engines. The idea of declarative HTML helpers is awesome!

    I have two quick questions:

    1. What license will Razor be released under?

    2. How would you escape '}' and '{' inside your code blocks for example:

    @if (String.IsNullOrEmpty(p.Name)) {
    }
    }

    How would I escape the inner '}' in this code?

    -Andrew (cowfarm.net)

  • @Gavin (and all others who call this spaghetti)

    If you put logic in your view, then yes, you are right and you have spaghetti code but the whole point of MVC, especially if combined with ViewModels, is that you can eliminate all logic within the view.

    Just a short example of "good" and "bad" use of inline code:

    Good:Hello@Model.WelcomeText

    Bad: Hello

  • The perfect mix of C# and HTML. I never liked using code blocks but felt like Spark was to invasive on my HTML markup. This seems to be the perfect balance... and it came from Microsoft??? ;)

  • Note about View/Logic separation comments:

    "Razor" do not replace Model and Controller, it's a bridge to render the View.

    You can also implement "ControllerAction" directly on cshtml.
    Sample:
    @{
    "controller action of view"
    }

    "view (html + code)"

  • @Scott,

    >>>>>>>>I believe that will work - but am not 100% sure. I believe our HTML intellisense is still schema driven - so you could create your own and get intellisnse for it within a razor file.

    I'll have to have a dig around and see. It would be great to be able to combine razor with the MVC Futures code that supports multiple representations, e.g. ABC.cshtml, ABC.xml.cshtml and ABC.json.cshtml (or should that be ABC.cshtml, ABC.csxml and ABC.csjson?).

  • This further proves my point that Microsoft has some of the smartest and most innovative developers on the planet. Excellent work, REALLY looking forward to giving it a shot. Much as I love Spark it feels too Cold Fusiony for me, really like what you guys are doing

  • This looks really great, I can't wait to get my hands on it :)

  • Interesting. But why not about eliminating '{' and having somenthing liike this:
    @if(cond):
    custom code
    @endif

    or

    @for():

    @endfor

  • Wonderful... this is what we are looking for...

  • Hi Scott,

    This is great. Is two-way data-binding of some sort on the MVC road map? For business applications we need a really "rapid" way to two-way databind to a single business data object (not tied to a database, necessarily) with validations and all that. And it would have to go beyond flat data - arbitrarily complex types with complex components as well. I've been frustrated for years on this. I may misunderstand MVC, but it seems to be a poor choice, currently, for business applications like this for exposing complex data structures for editing.

    Thanks!

  • Definitely a syntactical improvement over the default view engine asp.net ships with. Can't wait to see how well this work in a real project.

    -Jeff

  • Scott,

    What's about "updating" RenderBody, RenderSection, RenderPage, "RenderArea" without refreshing?!
    What's about "AJAX" (partial render, no refreshing) without need of jQuery, MS AJAX and others libs?!

    ...it's time to have this feature "Out-of-Box" on a core engine...

    Example: "A HTML5/CSS3 video site that needs to change a playlist without refreshing the whole site losing video context"

    This is looking great!
    Thanks

  • As some of them have pointed, I do have a concerns and worried about the current trend where people putting bulk of the code in the UI layer..

    Are we going back or forward..???

    By the way thanks Germian for considering my Article posted at CodeProject

  • My biggest complaint with the current aspx syntax would be the way it "stands out" from standard html code. It makes the code look messy and ugly. Razer is definitely a great step forward but the "@" prefix still kinda makes it stand out and somewhat limits the fluidity. How about using a colon ":" instead of "@"? :Model.Name looks a lot better than @Model.Name and merges with the code nicely.

  • I'm assuming the source code will be release as open source as the rest of MVC. Is this correct?

  • Wow... why not just go back to classic asp because this is what it reminds me of.

  • So - the family of the ASP.NET MVC engines keeps growing. This is good. I wonder how can I get on the list with my NDjango - a .NET port of very popular django templates written in F#. It comes with VS extension providing complete intellisense support

  • As Zebula noted it looks like asp classic. I had a ' wow amazing discovery!, they have invented asp classic with some enchancements' moment.


  • Classic asp? Somebody seems to have forgotten that old nightmare. Razor seems like a very good view engine which will eliminate a lot of the clutter in standard asp.net webforms view engine pages. Reminds me a little of Velocity, which is a good thing.

  • Interesting if we could generate XML/RSS/Atom (*.csxml) with "Razor".

    Scott?!

  • I'm quite excited.

    However, I am kind of stuck with vs2k8 for the foreseeable future. Is the source available, and do I have a chance at compiling it for .NET 3.5?

  • Razor looks amazing, I really like what I see. My main concern (and my concern with any view engine) is that I cannot easily migrate my aspx pages to the razor due to razor being incomparable with aspx master pages. This means that if I don't want to have to maintain duplicate master pages I have to migrate every one of my aspx views all at the same time instead of slowly migrating over a period of time (which will be much safer). Will there be any remedies to help with this?

  • WebGrid question:

    How can I insert a new column which is not linked to data source? I want to add Edit and Delete links for every records using WebGrid helper.

    Thanks and keep up the good work!

  • Great, but I'd sugest one more feature. It is about XML.

    If a variable have XmlDocument, DataSet or some any other type that supports XPath, I want to query it using simplified syntax. Instead using methods I like to use XPath just like I do it in XSLT:

    Instead: doc.SelectNodes("/product[position() = 3]/@title")
    Write: $doc/product[position() = 3]/@title

    And if result is used as a scalar value (assigned to a string or numeric context) - automatically get "Value" for XmlAttribute, "/text()" for XmlElement, etc.

  • Hi Scott (take this as a comment not as an attack) ,

    the work for sure is great but it lake of innovation , what I see is something look like JSTL ,and Servlet with JSP model . even if there are people who like this model it is really lake of any innovation .

    for me it is like comparing C#.Net with C++6 MFC in old days of Windows Form Development .

    what really make me worried about the future of ASP.NET :

    1-ASP.NET is doing things like what JAVA did in old days , waste of time.

    2- ORACLE bought Sun and JAVA,JSP,JSF now under them , imagine when ORACLE , get ride of those UNIX thinking guys who likes command prompt and get those guys that like drag drop and making life easier, and put a layer of decoration for all the JSP,JSF stuff to introduce all the power of these detaild complex features in anew easy way , THAT IS THE INNOVATION . They will have the same nice Visual Studio with all the cool features that ASP.NET had , because MVC was the core of JSP and JSF from the first .

    so when ASP.NET and JSF reach the same level of programming friendly model , what developers will choose ?

    The key here for the ASP.NET future is to innovate the Web not to return to old dark days.

    I am waiting the day to see the end days of javascript and hmtl formatting as a web developer. I need to know js,html,jquery,Razor ,blablabla to do my job , this reflect how ASP.NET still have many fields to innovate and introduce new ideas for web development .

    for example :

    if your team focus on ASP.NET eCommerce model , for me it was much way worth than MVC . ASP.NET still need to be specialized and be strong in many critical web fields ,why not we have a Products category control ,products control Shooping Cart control , payment gateway control integrated with Microsoft Money
    eCommerceProviderModel look like MembershipProviderModel !
    to build an eCommerce site in less than an hour , that is the Technology that I want to use .It is less than 1 year work from a small team inside Microsoft

    look to Google Checkout , and how they are attacking a critical area and give support for all even .NET and ASP.NET :
    http://code.google.com/apis/checkout/samples/Google_Checkout_Sample_Code_NET.html

    if you just play with Google Checkout (their eCommerce model) and old days eCommerce model , you will understand how Google is innovating and how they even will make a non programmer will be able to sell.

    Please Scott , tell the JAVA guys in ASP.NET team , stop copying JAVA instead you know JSP and JSF , innovate give us new ideas that make our daily web development interesting.

    I am really commenting not attacking I hope you got my points .

    one last thing Scott add innovation factor to all Microsoft hiring process , specially in the Jobs like Product Manager , there Should be a new Job called Product Innovator , working as a stage between what the customer want (Product
    Manager) and how it should be implemented (Program Manager) .

    the model is
    Product Manager->Program Manager
    it need this factor
    Product Manager - > Product Innovator - > Program Manager.

    anything that make Microsoft return to the top again as an innovator company.

    good work and keep innovation.



  • The Razor syntax seems cute and you save a few key strokes. But at what cost in terms of functionality, granular control, code behind ability and the view engine's overhead? Or is this just meant to be an alternative replacement for creating simple pages, that do not require more extensive functionality? If that's the case, yeah, it's good. Rock on.

  • Today, pure HTML + CSS do a great job where "Razor" is the best friend and "Helpers" will be welcome.
    Unlike applications, the good web experiences are not made by WebForms or Dreamweaver's.

  • By the way, I hope the comment above doesn't come across as negative, critical or anything other than a first impression, which it was. I have Web Matrix open right now. It is cute and easy to use. I think it will help to facilitate the adoption of the .NET platform by inexperienced users. And that is a good thing, to have more ASP.NET websites around. ASP.NET is after all, a great environment for developing quality, high performance, reliable applications.

  • Scott, Why invest in a new engine when you can take Spark engine and enhance it with IntelliSense and more Microsoft approach?

  • Ran,

    I think "Razor" is more easy, generic and .NET like than the "Spark".

  • It's a shame the MVC 3 Preview doesn't include support for Razor syntax highlighting / intellisense. It looks so beautiful...

  • Oh... very nice I Love Microsoft and ScottGu

  • very cool, I liked the syntax and the clean output

    keep going

  • It all looks great, but once again VB programmers are the red-headed step child of MS.

  • @demuggle,

    >>>>>>>>> Some people (GuruStop.NET) are speculating that this will make Web Forms obsolet. I did not get the impression from your post that this would be the case. Could you clarify on that?

    Web Forms is definitely not obsolete! We are investing heavily in that and it is a first class part of ASP.NET.

    Hope this helps,

    Scott

  • @Eric,

    >>>>>>>> It all looks great, but once again VB programmers are the red-headed step child of MS.

    Razor will support both VB and C# syntax. You'll definitely be able to use this with VB.

    Hope this helps,

    Scott

  • Hi Scott, first of all thanks for this great article, but I want to know that on which basis we can chose View Engine at the time of adding new view. If you provide some description or comparison of all the View engines then its great. Is it good practice to use different View Engines in same project?

  • I have been playing with Razor for a few hours converting an existing MVC 2 app. I have run into an issue. I am getting an error when using nesting control statements like if and foreach. Are nested control statements supported? If so is there a special syntax required for the Razor engine?

  • @demuggle
    I was talking about the webforms view engine (as in webforms view engine vs Razor view engine), not ASP.NET webforms technology itself (as in webforms vs MVC). I knew such naming confusion would sure happen!

    Still "obsolete" is also as in "LINQ To SQL is obsolete". The idea that it will still get important
    updates, features, etc, but will not be the recommended mainstream (maybe in official docs but not in reality).

    Still, would love a Scott comment on this more.


    Regarding ASP.NET webforms technology, I think it's a bit different mainly because of amount of existing investment by MS and component developers. Specifically SharePoint (and TFS and ...) and Telerik, etc...

  • @Wayne,

    >>>>>>>> I have been playing with Razor for a few hours converting an existing MVC 2 app. I have run into an issue. I am getting an error when using nesting control statements like if and foreach. Are nested control statements supported? If so is there a special syntax required for the Razor engine?

    Nested statements are definitely supported. Can you share a code snippet of what you are doing and what the error is? I can then help.

    Thanks,

    Scott

  • @Mohamed,

    >>>>>>>> I was talking about the webforms view engine (as in webforms view engine vs Razor view engine), not ASP.NET webforms technology itself (as in webforms vs MVC). I knew such naming confusion would sure happen!

    We don't think of it as obsolete. All of our HTML helper libraries will work with both the .ASPX and Razor view engines. You can also use .ASPX partials from within Razor views, and Razor partials within .ASPX views. So there are also a lot of interop scenarios enabled.

    I do think a lot of people will be interested in adopting Razor once the final release of it ships (and once intellisense comes online), since it doesn't involve too much of an additional learning curve over what people do today - and has the added benefit of being much more concise from a code/typing perspective.

    Hope this helps,

    Scott

  • This looks absolutely terrific! I just can't wait to start shaving :-)

  • Hi Scott,

    I just had a look at MVC 3 preview. The Spark Syntax looks great, but I am sorely missing Syntax highlighting and code completion. Is this going to be part of the next release?

    Thanks,

    Adrian

  • I'm looking at WebMatrix now, and the first thing I'd like to understand is where the Razor template engine is configured. The example site makes a reference to a class named Twitter, which apparently resides in Microsoft.WebPages.Helpers.Toolkit, but I can't find any place where the reference is configured. Is there documentation for this?

  • Sorry I totally do not agree mix code and ui again, feel like time roll back to asp age.
    Is microsoft getting into wrong way?

  • Why is MS mixing code and UI again? Wasn't the point of .NET to move forward and separate the two?

    I feel like this is going back to classic ASP

  • @Gavin,

    I totally agree.Everybody seems to be praising a step backwards,why? Just because it's new?
    Keep presentation and logic seperated,so much better.
    About the new Webmatrix: the only usable thing I see is the new sql ce integration, great !!
    (Oh, and the button which leads to VWD ;)

  • @Frank... OR... perhaps Microsoft went the wrong way when they forced the Stateful Forms model onto a Stateless Web form. Sure, it made development easier and convinced developers to go with the Microsoft web stack, so it did its job, but this allows the developer to better and more properly interact with the http protocol, instead of hiding everything behind a View State.

  • Excellent work..
    When ever there is a complex View, I used to generate HTML having large code block
    and use many Response.Write(). We do this to have a clean & readable code..

    Razor will be absorbed greatly

  • @ScottGu

    With @Razor(), how are you going to reply to people now? j/k.

    I don't like the syntax, it doesn't help when you need mix XML.

    Could we have something like @if{test} returns the text "test" and @if{@test} returns the variable test. To get around the problem 'what if my text has squiggly {} brackets,' maybe have use XML/HTML ASCII character codes, or have a special case?

    Adam.

    Adam.

  • @Adam,

    >>>>>> With @Razor(), how are you going to reply to people now? j/k.

    The good news is that the parser is smart enough to differentiate an email address from code :-)

    >>>>>>I don't like the syntax, it doesn't help when you need mix XML.

    Rather than use you can alternative write:

    if (somevar == true) {
    @:Some content @somevar
    }

    @: is equivalent to using the syntax when only a single line is output.

    Hope this helps,

    Scott

  • // in template
    @{ View.Title = "Home Page"; }
    read @View.Title
    // in controller
    ViewModel.Message = "foo";
    read @View.Message

    Why 'View' then 'ViewModel'?

  • Please, can you remove/replace using statement? Why such language construct should be in template?

    @using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    }

    @Html.BeginForm()
    @Html.ValidationSummary(true)
    @Html.EndForm()

    or even

    @Html.Form(new { autocomplete = "off" },
    @Html.ValidationSummary(true)
    )


  • Thanks for Introducing “Razor”
    Have some questions as
    In Adding Section
    “footer” section overrides is being
    defined within named @section { } blocks within the file Home.cshtml

    ok , I have some question on this

    Is that I have to add @section footer {} in all its subpage? Or I can put that section in another file. (Something footer.cshtml) as it was in master we use to add footer.ascx which we keep common for some pages.


    Thanks,
    Rajan J Dmello

  • @rjdmello,

    >>>>>>> Is that I have to add @section footer {} in all its subpage? Or I can put that section in another file. (Something footer.cshtml) as it was in master we use to add footer.ascx which we keep common for some pages.

    Yes - you can create what is called a "Partial" template that is used from the master-page (or a sub-page) and is encapsulated in a file like footer.ascx.

    To render it just write @Html.RenderPartial("footer") in either your master-page or the child-page.

    Hope this helps,

    Scott

  • How should we use custom helpers? I have created some of them, but when the view is shown it appears like this:

    Login

    instead of an html link.

  • Admittedly, it's easier on the eyes :-)

Comments have been disabled for this content.