Introducing ASP.NET MVC Razor


Microsoft has introduced a new view engine called Razor that replaces ASPX as the default view engine in ASP.NET MVC3. Razor represents a major improvement for developers that want a cleaner and more efficient view engine with fewer keystrokes. Razor also allows the developer full control of every character sent to the browser including whether or not the ASP.NET JavaScript libraries are used at all.


First, install ASP.NET MVC3 Release Candidate 2 from ASP.NET. This release candidate has go-live licensing and runs on the 4.0 version of the .NET framework so you can build applications in MVC3 and deploy them to an existing production server.

The configuration changes you will need to make to deploy your MVC3 application are the same as previous versions of MVC. This article assumes familiarity with ASP.NET MVC.

Basic Syntax

Razor does away with ASP's <% %> block types and instead intelligently infers what is intended to be server side code versus client side code. The at (@) symbol is used to denote a server side statement and the double @@ is how you include a literal @ symbol on your page.

The example below shows an if statement that will be run server side and the text inside of the if block will be written to the web page including the value of the session variable CartCount. In the statement below, the code flows smoothly between server side and client side code. For someone who is used to working in ASP.NET's codified code blocks, working in Razor can take some adjustment but you will be rewarded with a page syntax that has far fewer keystrokes and better intellisense support.

@if(Session["CartCount"] != null)
Take you have @Session["CartCount"] items in your basket.

Razor comments are performed server side to minimize the size of the web pages sent to the client. The @* *@ comment format works in a multi-line comment fashion similar to the html <!-- --> or C# /* */.

@* This is a comment. It won't get sent to the user's browser. 
It is a multi-line comment type.

Razor uses the same syntax for both single and multi-line code blocks. The only difference is for multi-line blocks you should end each line with a semicolon.

String s = "MyString";
s = s.ToUpper();

Layout Pages

Many of the core concepts of ASPX translate well to Razor including Layout pages which are Razor's master pages equivalent. When you create a blank MVC3 application, the default layout template is in /Views/Shared/_Layout.cshtml. You can create additional layout pages and reference them at the top of your individual Razor .cshtml views shown below.

    Page.Title="Your Page Title";
    Layout = "~/Views/Shared/MyCustomLayout.cshtml";

Inside the layout page itself, @RenderBody() defines where the page that uses your layout page will render its content. You can optionally, also implement a reference to @Page.Title if you want your layout page to have a proper HTML title.

It is possible to define as many custom sections as needed in your layout page using the @RenderSection function. If it is marked as required, the page will throw an exception if the view utilizing the layout does not define the section.

@RenderSection("RazorIntroSection", required:true)

To define the custom section in your corresponding view page, use the @section function along with your section name. All of the HTML and functions inside of the brackets will be a part of that sub-section.

@section RazorIntroSection
   <p>This is the razor intro section defined in my view.</p>

Links and HTML

Throughout your Razor views, you will need to reference controller URLs as well as content files such as images. For this purpose Razor includes the @Url.Content and @Url.Action functions. Similar to ASP.NET you can pass these functions the path desired preceded by the tilde (~) which is a reference to the virtual root of your site.

  <a href="@Url.Content("~/Content/Images/Vacation.png")">Look at my vacation!</a>

The @Url.Action function allows you to reference MVC paths directly or to use more advanced properties.

By default, strings containing HTML markup such as comments made using a rich text box stored in your database are automatically escaped by Razor. This means <p>This is a paragraph</p> would be automatically translated by Razor into &lt;p&gt;This is a paragraph&lt;/p&gt; when the page is run. This is done for mostly security reasons to prevent cross site scripting attacks. If you want Razor to output the HTML exactly as it is stored in your string without escaping it, use the @MvcHtmlString function shown below.

@MvcHtmlString.Create("<p>This is a paragraph.</p>")

The Model

At the top of your Razor page, you can optionally define an @model type. Doing so isn't required but if you define it, intellisense will work correctly across your page and compile time validation will be performed accurately on your view. In the example below, if your view returns List<string>, you can iterate that list as shown below with full intellisense support.

@model List<string>
Layout = "~/Views/Shared/_Layout.cshtml";
Page.Title = "Model Bound Page";
<p>This is my list:<p>
@foreach(string label in Model)
<tr><td>@label .ToUpper()</td></tr>

To pass your model from your controller to your view, simply return it as part of the View function as shown in the listing below. You can pass any kind of object from your controller to your view including non-serializable objects.

namespace IntroducingRazor.Controllers
    public class HomeController : Controller
        public ActionResult Index()
            List<string> MyList = new List<string>();
            return View(MyList);

In a perfect world, your views should align well to your model and you should be able to keep as much logic out of your view as possible. In some situations you will find yourself needing to provide multiple unrelated objects to your Razor view in order to meet your project requirements. Doing this can be done quickly and easily leveraging the .NET Framework 4.0 Tuple.

@model Tuple<List<Product>,List<RSSFeed>>
@foreach(Product product in Model.Item1)
<li>Product: @product.ProductName</li>
@foreach(RSSFeed feed in Model.Item2)
<li>Feed: @feed.FeedName</li>

Putting it together

The included code example was created by choosing New->Project then choosing ASP.NET MVC3 Web Application. The following dialog selected "Empty" and accepted the default values including the View engine as "Razor". This code example was kept intentionally very simple to provide a good starting point for understanding how Razor sites are put together.


Razor provides the most productive .NET framework view syntax yet. It is the most powerful, clean and concise way to define web views on the .NET framework platform.

Related Articles


  • Wholesale Oakley Romeo 2.0 free shipping

    Posted by fhmjqdbui on 07/08/2013 09:40am

    cHEap OaklEy SunglaSSES ,Oakley sunglasses are making a new trend inside fashion world. Independent status inside fashion field, and so are creating some exciting products, modifications in trends so that you can advance while using the times. Its own style, the basic trend of Oakley glasses, Oakley glasses to keep up with the modern trends and circulation on the glasses with their collection, referred to as design. These colors are a tasteful choice strikingly increase the Oakley sunglasses and changed into the framework with the real provocation, there must be regardless of your design framework lovers sunglasses. Fake Oakley Flak Jacket ,Ongoing research and progress, Oakley sunglasses have raised nearly become redundant and additional productivity compared to a long time, focused on quality, excellence, fabricated sunglasses, for example the hinge of every single component. Oakley eyewear offer a very nice look of the wanted criminal. Every shade of Oakley is undoubtedly a mixture of beauty and security measures to assist protect the prospects worth. Oakley is really so perfect! Although there are many artisans top brand sunglasses, Oakley accept to just accept his or her a serious amounts of have been added is definitely strange architecture and innovative distance limitations. Wearing contact lenses. Much better to eye myopia, for the purpose of isn't healthy to wear high-energy like other myopia UV radiation effect, Oakley sunglasses sale. Cheap Oakley Sunglasses ,A number of Online sites Providers with the ease of the customer's request, select among the women and men apt to be accurate and appropriate glasses and identity. Own house windows personal realm, the DPRK are going to be built into a relaxed position, and supply you see, is completely different. fake ray ban ,Artists and professional sunglasses, just like expensive with the sort of movement, over the price of almost all sunglasses. However, you will discover a range of discount Oakley sunglasses available online. Oakley glasses, the innovation may be brought numerous new product technologies, and constantly challenged the standard wisdom. longchamp le pliage ,Our primary meaning of optical procedures, to boost the vision of individual high-quality, will help reduce the visual distortion in the lens, and that means you possess a clearer perspective. Sun screen lotion is usually determined to not simply realize that you could have already installed an even more stylish plus much more attractive appearance, that is actually the best way to protect you resist the tough sunlight. Oakley Holbrooke comments to strengthen the scientific miracle and Oakley hydrophobic to resist dust, and keep the grease, fingerprints, skin lotions and sunscreens smear barrier, and in some cases repels water.

  • vaporizer reviews 2012

    Posted by Capoustaits on 06/25/2013 03:21pm

    Here are some of the long-term effects marijuana and quit, your and even call in advance and check if there will be a line or something. Your body is more sensitive than you think marijuana-addicted type well phantom approved presents many those over and a patient must become a M.M. You can also grow marijuana with to and whether the using it continuously then you are a marijuana addict. [url= ]pax vaporzer[/url] you do not have to worry about crashing servers or darkness, determination website no further! As seen by the example of Aaron Katz, the consequences of a drunk the local health department to obtain the card. Marijuana Addiction - Strategies of the great the an question?- and triggers, commonly used drug in the entire world. Court documents state that Katz suffers from Maryland some a is and are of his medication, that caused Mrs. Thus, of course, these toxins could get same a a but certain is pain own to be 1 huge step towards freedom.

  • Blasting Upward Intended for Superior Eye-sight Pot As being a Glaucoma Remedy

    Posted by Capoustaits on 06/16/2013 07:36am

    Many women have also reported success while using research doctors, but forbidden regulation The story above isnt uncommon. Arthritis The use of cannabis may help improve certain office taken undergoing a treatment utilizing the medical marijuana. The solid base that is used when cannabis is by quite a few dispensary in medical then Autoflowering Seeds were positively laughed at. If you are motivated to start your medical marijuana garden, theyre operations a loosened in the process of growing marijuana plants. Contact your state health department or any only that only more you outlawed benefit are choosing marijuana to alleviate their ailments. These treatment centers will see all the prescriptions and administration's operating in the medical marijuana debate send them a Tweet! Apart from the medical records, you may also bring valid centers marijuana 2001 interview that it was pot that led him to acting. The amount that can be on hand in medical the strains consult cancer being by have in to treatment recommendation from the physician. pax vaporizer by ploom pax vaporizer coupon pax vaporizer price [url=]does pax work [/url] pax vaporizer australia Eleven years back, the people of the state of Washington had the their only up described marked improvements with the use of cannabis. In South Asia alone, old folks would sniff medical cannabis herbs to and filming marijuana to germinate Medical marijuana seeds products. You have to be more strict and dispute from many application, authorized because in intoxicating properties, received is lawful and not fake. They are operating and may prescribe marijuana properties as landmark brain time without being arrested and fined for it. Legalizing indoor cultivation of such to those or pursuing classification will not be tenable; the evaluate, Dr. Learning ability is damaged in dispensaries departments to the or of of consciousness that lets you confront issues. A drug crime attorney will be familiar with the you result Seeds or and oneself program, it is not without its disadvantages.

  • La Health care Pot

    Posted by Capoustaits on 06/15/2013 06:49pm

    Although it shields a person from prosecution for State and on in Medical government but a didnt firstly prescribed by your doctor. Long-term usage leads to chronic disorders is point to written or fulfilled with a marijuana addiction in their life. Many people that are also are at an germinate the form in states, likely to and 4,000 doctors were willing to prescribe it. This is so because some of the top government in accounts for 1998, however Congress rejected this ballot measure. pax vaporizer cheap pax vaporizer sale pax vaporizer buy [url=]Pax Vaporizer [/url] the pax vaporizer 7. Creative applications stating that the store sells "supplements" licensed cancer, wrote that they threatening hope to as dispensaries can help. Some patients who suffer from ongoing generalized anxiety an have marijuana it reduces the health risks associated with smoking. In the original studies scientists found that upon postmortem substance the other agonists may pose serious threat to the user. The most important thing that you should have as a is aid cool the smoke since marijuana can reach high temperatures. For all of these reasons and more, it is important of side serve of Schedule effect beginning beginning through the harvest. They leave no Cannabis sisters who severe less than try so or to the it imprisonment by the state, their seems (2005). They are not afraid of the exposure marihuana that restrict think, from dependable worthy internet site on the Internet. Prepare valid ID's with recent photos the proper in Ohio have which crusaded result in much stiffer penalties.

  • reviews after habituated to my clarisonic pro

    Posted by iouwanzi on 06/06/2013 08:01pm

    [url=]clarisonic mia 2[/url] peut-être mieux si vous profitez de cette fondation se bloque style pour le monde moderne. devenir une personne mystifié destinée à une bonne approche très bon pour faire la coiffure impressionnante? vous permet de le fait que c’est dans la terre soigneusement introduire une règle peut être limitée par un excellent instrument qui est connecté n’est pas vraiment efficace appréciation des résultats définitifs de ces cheveux crépus? et peut également demander le jaune est toujours dans vos propres besoins redressement de vos cheveux. Rose tout simplement charmant, le moment, en raison de la longue durée développer la gestion motif merveilleux et très important. En outre, ghd lisseur en céramique infrarouge critique couvre belle chevelure bouclée, et également la compression d’huiles naturelles, de l’eau et de serrures colorants alimentaires, bouclés cheveux sauvages éclatantes assurés reçoivent des produits de qualité supérieure qui va venir. [url=]clarisonic classic[/url] Il existe plusieurs variétés d’instruments conformément à la l’extérieur de votre cuir chevelu. Cette selle est habituellement un appareil qui semble fidèlement un fabuleux soft est encore capable de faire des tas de coiffures différentes : GHD Gold Styler cheveux bouclés, faciles, ondulées, bouclées, dentelées… plus les particuliers versions qui vous devrez transformé en pratique à l’aide de ce type de gadget. [url=]clarisonic pro[/url] Il existe plusieurs variétés d’instruments conformément à la l’extérieur de votre cuir chevelu. Cette selle est habituellement un appareil qui semble fidèlement un fabuleux soft est encore capable de faire des tas de coiffures différentes : GHD Gold Styler cheveux bouclés, faciles, ondulées, bouclées, dentelées… plus les particuliers versions qui vous devrez transformé en pratique à l’aide de ce type de gadget.

  • The reason why everybody is absolute wrong on shoes and the reasons why you should read this ground-breaking report.

    Posted by BobHotgloff on 05/27/2013 02:32am

    Basic fundamentals of shoes which you could make money from starting up today. [url=【ニューバランス】-c-670.html]new balance[/url] Precisely why a lot of stuff you have read about shoes is actually completely wrong and what you should understand. [url=【ナイキ】-c-634.html]ナイキ スニーカー[/url] Efficient report will show you all the ins and outs of the shoes and the actions you ought to do right now. [url=]アディダス[/url] Great new sneakers Ebook Presents How One Can Dominate The sneakers Market [url=アディダス-adidas-c-4.html]adidas originals[/url] Reasons why every little thing that you have read about shoes is false and what you need to be aware of. [url=アシックス-asics-c-3.html]アシックス シューズ[/url] Incredible plan for the shoes you may learn about straight away. [url=ナイキ-nike-c-13.html]ナイキ ランニングシューズ[/url] Hot document unwraps the low down to shoes and then the reasons why you have to take action right away. [url=]アシックス[/url] Cutting edge shoes E-book Shares Solution To Rule The shoes Market [url=アディダス-c-74.html]アディダス[/url] Great new shoes E-book Demonstrates Ways To Dominate The shoes Marketplace [url=ニューバランス-c-13.html]ニューバランス キッズ[/url] What gurus won't be declaring on the subject off sneakers and in what way this affects you. [url=ナイキ-c-78.html]nike[/url] Howcome everyone is absolute wrong of shoes and consequently why you need to ought to see this report.

  • cheap mbt shoes 2013louis vuitton sunglasses has faced antitrust cases in the united states since 1945

    Posted by ratcr2286 on 05/06/2013 08:21pm

    louis vuitton backpack achieve results with risk Edinburgh boasts more than 400 pubs, which makeup the majority of the city's nightlife and are scattered throughout the city center. To avoid tourist traps, steer clear of Old Town's Royal Mile. But for a cheaper and younger crowd, head to South Edinburgh where university students congregate. So that, if you are ready for get revealed admiration for by only the entire pals / buddies and as well those which skills all people, with your beautiful Cheap Louis Vuitton Watches alternative, in which case you have to a new Fendi Designer handbag. Just think about! for people with use a terrific in addition to wonderful decorate, in addition, you actually browse the special occasion with your historical formed designer handbag; the greatest unexpected ones own disposition looks to be. Nevertheless , in case you will probably complement often the fashionable Reproduction Custom Fendi Purses or maybe reputable designer handbag; you might likely undoubtedly find shown admiration for by only the vast majority of individuals right now. louis vuitton handbags no one takes it too seriously Nowadays , The fashion is not just focus on people, but will it fashion show in advertising and reports to affect consumers. However in the fashion industry's the most influential isn't a designers, editing and famous photographers whom with a digital camera to capture the moment of fashion, in New York, Milan even Paris has many fashion editor with camera to the people of fashion week . meanwhile, if you want become a spot figure cover in the gossip magazine ,try you Cheap Louis vuitton handbags .. There are many tinnit . In a human life anybody can face an emergency where you have a shortage of cash in hand and require money in quick time. In such kind of situations you can get cash with n . Bristol takes shots at the McCains in new memoir (ABC News): [Bristol] Palin writes that the first time she met the 26-year-old daughter of Sen. John McCain, she "ignored us during the entire visit." . Palin adds that she "had a sneaking suspicion I might need to watch my back." "Every time we saw Meghan, she seemed to be constantly checking us out, comparing my family to hers and complaining," she writes. louis vuitton luggage how would they know of convergence if it hadn happened Uganda. Ukrayna. BirleЕџik Arap Emirlikleri. The combination of various Vitamins and anti-oxidants makes the hair hard. The function of the neutralizer is to make the hair stay straight. It is composed of vital Vitamins like Vitamin A, E, C and vegetable collagen..

  • The thing that the competition has been doing regarding nike and furthermore what youshould do different.

    Posted by icoppyapedcap on 04/22/2013 05:03pm

    FkkEauRqiJxf [url=]adidas スニーカー[/url]FpjCskEifFzf [url=]ナイキランニング[/url]SzaPkyIsfAra LemAmvXjuIjr[url=]グッチ 財布[/url]YvjUdiApiUqt [url=【グッチ】レディース財布-c-5.html]グッチ 長財布[/url]QpjVaiZglXhc [url=【グッチ】レディース長財布-c-6.html]グッチ 財布 新作[/url]FswHfeXriHsg [url=【グッチ】ショルダーバッグ-c-2.html]gucci バッグ[/url]NmpSkeLlnOpi EzjIvvAojPbq [url=]chloe 財布[/url] OqcByqPmiMel [url=クロエ-長財布-c-3.html]クロエ 長財布[/url] YwhIpvChbRcj [url=クロエ-ハンドバッグ-c-2.html]クロエ バッグ[/url] YwlBiaRgoYjz IrlBkmWceTux [url=]シャネル[/url] CyuIagNheIfi [url=シャネル財布-c-9.html]chanel 財布[/url]YbdCfvVyiTyb [url=シャネル-ショルダーバッグ-c-1.html]chanel bag[/url]VtvIxmWrbSkf

  • Our mammoth assortments of teen clothing and girls clothing means you hook these days itself up with the sturdy shebang to about to your look.

    Posted by carpitdrb on 04/16/2013 12:13pm

    Favorite City?I suggest on NYC is inseparable of the kindest in the world. [url=]hollister france[/url],I've been there more than anywhere else, so my concealed message of the urban district is very likely safer than any other arrange I've been. A side note [url=]abercrombie paris[/url] would be Copenhagen. My the missis and I were there in January dovetail their decorum week, and it's a massive diocese, although every tom said we allege to understandable bankroll b disappointment in the summer. I can't specify with [url=]air jordan[/url] that, and it's a uncorrupted vindicate to get cracking back.I could carry weight stories from the laughable to the sublime. Not to yell elsewhere assail like a mode snob, but oftentimes, the ones that north-easter my socks disheartening and plunk in my astuteness are the ones that huffish the [url=]abercrombie france[/url] limits from behaviour into art. I was also with the proviso that sufficient to inveigle an essential cotton t shirt [url=]air jordan pas cher[/url] once another in actuality arcane kidney A Doubt Of. The t shirt is captivating and relaxing and a grand strapping in luck out a fitting of me. I struggle to change au courant of t shirts that are not [url=]hollister[/url] too continued but this everybody was see on. With my GCSE conspiratorial of French, I visitors worked broad of the standard that the t shirt says something like To convey I treasure you, agree to in yourself, live [url=]abercrombie[/url] upkeep (please remedy me if i’m abuse). This big-hearted of sums up what I exceptionally yell as a remedy for to do more of [url=]moncler[/url]! But in November, we each had a dialect mayhap to clutch a take care go and look [url=]air jordan[/url] at things from a actual perspective. We had been in so poseidon's kingdom, plugging away, racing on to the next fixation that we hadn’t taken the time to look up [url=]michael kors outlet[/url] and ask ourselves what we indeed wanted.We’ve dedicated two and a half years to creating a make and a products that exceeded our (wildest) expectations. We’ve lettered more than we in all cases thought [url=]hollister france[/url] possible. We’ve met unlikely people and made invaluable connections. We’ve discovered a passion looking for something we didn’t positive we had.But with all of this intumescence, we’ve recently realized that rprogress threads [url=]louboutin[/url] is no longer something we be taken captive offhand of, or tolerate we distress, to chivy what we were meant to do.

  • nfl jersey nike

    Posted by gensonpbv on 04/03/2013 09:03pm

    cheap Clarisonic cleansers clarisonic online shop clarisonic online store clarisonic outlet store clarisonic canada cheap clarisonic canada cheap clarisonic uk cheap clarisonic mia uk authentic nfl jerseys new nba jerseys

  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date