SlideShare a Scribd company logo
1 of 34
Razor in MVC (View)


  Eyal Vardi
  CEO E4D Solutions LTD
  Microsoft MVP Visual C#
  blog: www.eVardi.com
Agenda
           Razor Syntax

           Master-Page View

           Partial View

           Helper Classes




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Razor Syntax




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Razor Design Goals
           Compact, Expressive, and Fluid

           Easy to Learn

           Is not a new language

           Works with any Text Editor

           Has great Intellisense

           Unit Testable

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
What To Choose?




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
ASPX vs. Razor




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
ASPX vs. Razor




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Single Statement Blocks
                        <!-- Single statement blocks -->
                        @{ var total = 7; }
                        @{ var myMessage = "Hello World"; }

                        <!-- Inline expressions -->
                        <p>The value of your account is: @total </p>
                        <p>The value of myMessage is: @myMessage</p>




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Multi-Statement Block
           <!-- Multi-statement block -->
           @{
               var greeting = "Welcome to our site!";
               var weekDay = DateTime.Now.DayOfWeek;
               var greetingMessage = greeting + " Today is: " + weekDay;
           }

           <p>The greeting is: @greetingMessage</p>




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Lines of Content
      @for( int i=0 ; i < 3 ; i++ )
      {
          @:Line <b>@i</b> of content <br/>
      }

      // Option II

      @for( int i=0 ; i < 3 ; i++ )
      {
          <text>
            Line <b>@i</b> of content <br/>
          </text>
       }




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Code Comments
                          @*     A one-line code comment. *@


                          @*
                                 This is a multiline code comment.
                                 It can continue for any number of lines.
                          *@


                         @{
                                 @* This is a comment. *@
                                 @* var theVar = 17; *@
                          }


                         @{
                                 // This is a comment.
                                 var myVar = 17;
                                 /* This is a multi-line comment
                                       that uses C# commenting syntax. */
                          }
© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Master Page




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
RenderPage




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
@Html.Partial()
                     <html>                                                      E4D.cshtml
                       <body>
                         @Html.Partial("PartialIndex");

                           @RenderBody()

                       </body>
                     </html>




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Master Page
      <!DOCTYPE html>                     E4D.cshtml
      <html>
          <body>
              <div id="Header">My Header</div>
              <div id="main">
                  @RenderBody()
              </div>
          </body>
      </html>      @{                                                            Index.cshtml
                       Layout = "~/Views/Shared/E4D.cshtml";
                       ViewBag.Title = "Home Page";
                   }
                   <h2>@ViewBag.Message</h2>
                   <p>
                       @{
                            for( int i=0 ; i < 5 ; i++ ) {
                                <b>Hello World.</b><br/>
                            }
                        }
                   </p>

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Master Page




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
The _ViewStart File
           Can be used to define common view code that
            you want to execute at the start of each View’s
            rendering.

      @{                                              _ViewStart.cshtml

             Layout = "~/Views/Shared/E4D.cshtml";
      }




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Layout Section
      <html>                                                                     E4D.cshtml
        <head>ASP.NET MVC 3.0</head>
        <body>
            @RenderSection("Header")
            @RenderBody()
            @RenderSection("Footer", required: false)
        </body>
      </html>



                          @{ Layout = "~/Views/Shared/_Layout.cshtml"; }  Index.cshtml
                          <html>
                             <head>ASP.NET MVC 3.0</head>
                             <body>
                                 @section Header { <div>Header content</div> }
                                 <div>Body Content</div>
                                 @section Footer { <div>Footer content</div> }
                             </body>
                          </html>

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Master Page & Sections




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
IsSectionDefined method
           The IsSectionDefined method returns true if
            a child content page defined a section.

                     <html>                                                      E4D.cshtml
                       <body>
                         @RenderBody()

                         @if ( IsSectionDefined("OptionalContent") )
                         {
                             @RenderSection("OptionalContent")
                         }
                         else
                         {
                             <div>Default content</div>
                         }
                       </body>
                     </html>


© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Use Razor Inline Templates
      public static class SectionExtensions
      {
          private static readonly object _o = new object();
          public static HelperResult RenderSection(
                      this WebPageBase page, string sectionName,
                                      Func<object, HelperResult> defaultContent)
          {
              if (page.IsSectionDefined(sectionName))
                   return page.RenderSection(sectionName);
              else
                   return defaultContent(_o);

             }              <body>
      }                      ...
                             @this.RenderSection( "Footer",
                                                  @<div>Default content</div>)
                            </body>




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Passing Data to Layout Pages




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
PageData Collection
      <html>                                                                     E4D.cshtml
        <head>@PageData["Title"]</head>
        <body>
            @RenderSection("Header")
            @RenderBody()
            @RenderSection("Footer", required: false)
        </body>
      </html>


                  @{ Layout = "~/Views/Shared/_Layout.cshtml";         Index.cshtml
                     @PageData["Title"] = “Passing Datat to Layout”;
                   }
                  <html>
                     <head>ASP.NET MVC 3.0</head>
                     <body>
                         @Section("Header"){ <div>Header content</div> }
                         <div>Body Content</div>
                         @Section("Footer"){ <div>Footer content</div> }
                     </body>
                  </html>

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
HTML Helper




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
HtmlHelper Class
           Helper methods and extensions are called
            using the Html property of the view, which is
            an instance of the HtmlHelper class.
                  Extension methods for the HtmlHelper class are in the
                   System.Web.Mvc.Html namespace.



                        @Html.CheckBox("Test it");




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Basic HTML Helpers
           ActionLink                                                   ListBox

           BeginForm                                                    Password

           CheckBox                                                     RadioButton

           DropDownList                                                 TextArea

           Hidden                                                       TextBox




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Basic HTML Helpers


© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Advance HTML Helpers
           Chart
                  Renders a chart, offering the same features as the chart control in
                   ASP.NET 4.

           WebGrid
                  Renders a data grid, complete with paging and sorting functionality.

           Crypto
                  Uses hashing algorithms to create properly salted and hashed
                   passwords.

           WebImage
           WebMail

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Advance HTML
          Helpers


© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
@helper Syntax




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
@helpers Across Multiple Views




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Custom HTML Helper
      public static class LabelExtensions
      {
         public static string Label(
                  this HtmlHelper helper, string target, string text)
         {
             return String
                      .Format("<label for='{0}'>{1}</label>", target, text);
         }
      }




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
TagBuilder Class
           Represents a class that is used by HTML
            helpers to build HTML elements.
      public static class ImageHelper
      {
         public static MvcHtmlString Image(this HtmlHelper helper, string id,
                                                       string url, string alt)
         {
             var builder = new TagBuilder("img");
             builder.GenerateId(id);

                  // Add attributes
                  builder.MergeAttribute("src", url);
                  builder.MergeAttribute("alt", alt);

                  return new MvcHtmlString(
                                     builder.ToString(TagRenderMode.SelfClosing) );
           }
      }

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Custom HTML Helper


© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il

More Related Content

Viewers also liked

Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
Domenic Denicola
 

Viewers also liked (20)

Leveraging Continuous Integration For Fun And Profit!
Leveraging Continuous Integration For Fun And Profit!Leveraging Continuous Integration For Fun And Profit!
Leveraging Continuous Integration For Fun And Profit!
 
Introducing Razor - A new view engine for ASP.NET
Introducing Razor - A new view engine for ASP.NET Introducing Razor - A new view engine for ASP.NET
Introducing Razor - A new view engine for ASP.NET
 
Razor and the Art of Templating
Razor and the Art of TemplatingRazor and the Art of Templating
Razor and the Art of Templating
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Async Frontiers
Async FrontiersAsync Frontiers
Async Frontiers
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
 
Angular 2 NgModule
Angular 2 NgModuleAngular 2 NgModule
Angular 2 NgModule
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
 
Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xUpgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.x
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
 
Angular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationAngular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time Compilation
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2
 
Angular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.xAngular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.x
 
Creating Custom HTML Helpers in ASP.NET MVC
Creating Custom HTML Helpers in ASP.NET MVCCreating Custom HTML Helpers in ASP.NET MVC
Creating Custom HTML Helpers in ASP.NET MVC
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipes
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
 
Scaffolding in One Asp.Net
Scaffolding in One Asp.NetScaffolding in One Asp.Net
Scaffolding in One Asp.Net
 

Similar to Views

Intro to MVC 3 for Government Developers
Intro to MVC 3 for Government DevelopersIntro to MVC 3 for Government Developers
Intro to MVC 3 for Government Developers
Frank La Vigne
 
C3 웹기술로만드는모바일앱
C3 웹기술로만드는모바일앱C3 웹기술로만드는모바일앱
C3 웹기술로만드는모바일앱
NAVER D2
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
snopteck
 
3 coding101 fewd_lesson3_your_first_website 20210105
3 coding101 fewd_lesson3_your_first_website 202101053 coding101 fewd_lesson3_your_first_website 20210105
3 coding101 fewd_lesson3_your_first_website 20210105
John Picasso
 
How Scala, Wicket, and Java EE Can Improve Web Development
How Scala, Wicket, and Java EE Can Improve Web DevelopmentHow Scala, Wicket, and Java EE Can Improve Web Development
How Scala, Wicket, and Java EE Can Improve Web Development
Bruno Borges
 
How to create a basic template
How to create a basic templateHow to create a basic template
How to create a basic template
vathur
 

Similar to Views (20)

AMD & Require.js
AMD & Require.jsAMD & Require.js
AMD & Require.js
 
Asp.Net Mvc Internals &amp; Extensibility
Asp.Net Mvc Internals &amp; ExtensibilityAsp.Net Mvc Internals &amp; Extensibility
Asp.Net Mvc Internals &amp; Extensibility
 
Web api crud operations
Web api crud operationsWeb api crud operations
Web api crud operations
 
Asp.net mvc internals & extensibility
Asp.net mvc internals & extensibilityAsp.net mvc internals & extensibility
Asp.net mvc internals & extensibility
 
Intro to MVC 3 for Government Developers
Intro to MVC 3 for Government DevelopersIntro to MVC 3 for Government Developers
Intro to MVC 3 for Government Developers
 
C3 웹기술로만드는모바일앱
C3 웹기술로만드는모바일앱C3 웹기술로만드는모바일앱
C3 웹기술로만드는모바일앱
 
HyperText Markup Language - HTML
HyperText Markup Language - HTMLHyperText Markup Language - HTML
HyperText Markup Language - HTML
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
Developing Your Ultimate Package
Developing Your Ultimate PackageDeveloping Your Ultimate Package
Developing Your Ultimate Package
 
3 coding101 fewd_lesson3_your_first_website 20210105
3 coding101 fewd_lesson3_your_first_website 202101053 coding101 fewd_lesson3_your_first_website 20210105
3 coding101 fewd_lesson3_your_first_website 20210105
 
HTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts BasicsHTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts Basics
 
How Scala, Wicket, and Java EE Can Improve Web Development
How Scala, Wicket, and Java EE Can Improve Web DevelopmentHow Scala, Wicket, and Java EE Can Improve Web Development
How Scala, Wicket, and Java EE Can Improve Web Development
 
How Akamai Made ESI Testing Simpler
How Akamai Made ESI Testing SimplerHow Akamai Made ESI Testing Simpler
How Akamai Made ESI Testing Simpler
 
Asp.net web api extensibility
Asp.net web api extensibilityAsp.net web api extensibility
Asp.net web api extensibility
 
Introduction to Zend Framework
Introduction to Zend FrameworkIntroduction to Zend Framework
Introduction to Zend Framework
 
Ed presents JSF 2.2 and WebSocket to Gameduell.
Ed presents JSF 2.2 and WebSocket to Gameduell.Ed presents JSF 2.2 and WebSocket to Gameduell.
Ed presents JSF 2.2 and WebSocket to Gameduell.
 
Coding for entrepreneurs
Coding for entrepreneursCoding for entrepreneurs
Coding for entrepreneurs
 
07 response-headers
07 response-headers07 response-headers
07 response-headers
 
How to create a basic template
How to create a basic templateHow to create a basic template
How to create a basic template
 
1.1 html lec 1
1.1 html lec 11.1 html lec 1
1.1 html lec 1
 

More from Eyal Vardi

More from Eyal Vardi (19)

Why magic
Why magicWhy magic
Why magic
 
Smart Contract
Smart ContractSmart Contract
Smart Contract
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 Architecture
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 Views
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScript
 
Angular 2.0 Pipes
Angular 2.0 PipesAngular 2.0 Pipes
Angular 2.0 Pipes
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Modules and injector
Modules and injectorModules and injector
Modules and injector
 
Modules in ECMAScript 6.0
Modules in ECMAScript 6.0Modules in ECMAScript 6.0
Modules in ECMAScript 6.0
 
Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0
 
Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0
 
Symbols in ECMAScript 6.0
Symbols in ECMAScript 6.0Symbols in ECMAScript 6.0
Symbols in ECMAScript 6.0
 
Objects & Classes in ECMAScript 6.0
Objects & Classes in ECMAScript 6.0Objects & Classes in ECMAScript 6.0
Objects & Classes in ECMAScript 6.0
 
Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS Internal
 
Node.js Spplication Scaling
Node.js Spplication ScalingNode.js Spplication Scaling
Node.js Spplication Scaling
 
Node.js Socket.IO
Node.js  Socket.IONode.js  Socket.IO
Node.js Socket.IO
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Recently uploaded (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Views

  • 1. Razor in MVC (View) Eyal Vardi CEO E4D Solutions LTD Microsoft MVP Visual C# blog: www.eVardi.com
  • 2. Agenda  Razor Syntax  Master-Page View  Partial View  Helper Classes © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 3. Razor Syntax © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 4. Razor Design Goals  Compact, Expressive, and Fluid  Easy to Learn  Is not a new language  Works with any Text Editor  Has great Intellisense  Unit Testable © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 5. What To Choose? © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 6. ASPX vs. Razor © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 7. ASPX vs. Razor © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 8. Single Statement Blocks <!-- Single statement blocks --> @{ var total = 7; } @{ var myMessage = "Hello World"; } <!-- Inline expressions --> <p>The value of your account is: @total </p> <p>The value of myMessage is: @myMessage</p> © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 9. Multi-Statement Block <!-- Multi-statement block --> @{ var greeting = "Welcome to our site!"; var weekDay = DateTime.Now.DayOfWeek; var greetingMessage = greeting + " Today is: " + weekDay; } <p>The greeting is: @greetingMessage</p> © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 10. Lines of Content @for( int i=0 ; i < 3 ; i++ ) { @:Line <b>@i</b> of content <br/> } // Option II @for( int i=0 ; i < 3 ; i++ ) { <text> Line <b>@i</b> of content <br/> </text> } © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 11. Code Comments @* A one-line code comment. *@ @* This is a multiline code comment. It can continue for any number of lines. *@ @{ @* This is a comment. *@ @* var theVar = 17; *@ } @{ // This is a comment. var myVar = 17; /* This is a multi-line comment that uses C# commenting syntax. */ } © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 12. Master Page © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 13. RenderPage © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 14. @Html.Partial() <html> E4D.cshtml <body> @Html.Partial("PartialIndex"); @RenderBody() </body> </html> © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 15. Master Page <!DOCTYPE html> E4D.cshtml <html> <body> <div id="Header">My Header</div> <div id="main"> @RenderBody() </div> </body> </html> @{ Index.cshtml Layout = "~/Views/Shared/E4D.cshtml"; ViewBag.Title = "Home Page"; } <h2>@ViewBag.Message</h2> <p> @{ for( int i=0 ; i < 5 ; i++ ) { <b>Hello World.</b><br/> } } </p> © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 16. Master Page © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 17. The _ViewStart File  Can be used to define common view code that you want to execute at the start of each View’s rendering. @{ _ViewStart.cshtml Layout = "~/Views/Shared/E4D.cshtml"; } © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 18. Layout Section <html> E4D.cshtml <head>ASP.NET MVC 3.0</head> <body> @RenderSection("Header") @RenderBody() @RenderSection("Footer", required: false) </body> </html> @{ Layout = "~/Views/Shared/_Layout.cshtml"; } Index.cshtml <html> <head>ASP.NET MVC 3.0</head> <body> @section Header { <div>Header content</div> } <div>Body Content</div> @section Footer { <div>Footer content</div> } </body> </html> © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 19. Master Page & Sections © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 20. IsSectionDefined method  The IsSectionDefined method returns true if a child content page defined a section. <html> E4D.cshtml <body> @RenderBody() @if ( IsSectionDefined("OptionalContent") ) { @RenderSection("OptionalContent") } else { <div>Default content</div> } </body> </html> © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 21. Use Razor Inline Templates public static class SectionExtensions { private static readonly object _o = new object(); public static HelperResult RenderSection( this WebPageBase page, string sectionName, Func<object, HelperResult> defaultContent) { if (page.IsSectionDefined(sectionName)) return page.RenderSection(sectionName); else return defaultContent(_o); } <body> } ... @this.RenderSection( "Footer", @<div>Default content</div>) </body> © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 22. Passing Data to Layout Pages © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 23. PageData Collection <html> E4D.cshtml <head>@PageData["Title"]</head> <body> @RenderSection("Header") @RenderBody() @RenderSection("Footer", required: false) </body> </html> @{ Layout = "~/Views/Shared/_Layout.cshtml"; Index.cshtml @PageData["Title"] = “Passing Datat to Layout”; } <html> <head>ASP.NET MVC 3.0</head> <body> @Section("Header"){ <div>Header content</div> } <div>Body Content</div> @Section("Footer"){ <div>Footer content</div> } </body> </html> © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 24. HTML Helper © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 25. HtmlHelper Class  Helper methods and extensions are called using the Html property of the view, which is an instance of the HtmlHelper class.  Extension methods for the HtmlHelper class are in the System.Web.Mvc.Html namespace. @Html.CheckBox("Test it"); © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 26. Basic HTML Helpers  ActionLink  ListBox  BeginForm  Password  CheckBox  RadioButton  DropDownList  TextArea  Hidden  TextBox © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 27. Basic HTML Helpers © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 28. Advance HTML Helpers  Chart  Renders a chart, offering the same features as the chart control in ASP.NET 4.  WebGrid  Renders a data grid, complete with paging and sorting functionality.  Crypto  Uses hashing algorithms to create properly salted and hashed passwords.  WebImage  WebMail © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 29. Advance HTML Helpers © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 30. @helper Syntax © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 31. @helpers Across Multiple Views © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 32. Custom HTML Helper public static class LabelExtensions { public static string Label( this HtmlHelper helper, string target, string text) { return String .Format("<label for='{0}'>{1}</label>", target, text); } } © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 33. TagBuilder Class  Represents a class that is used by HTML helpers to build HTML elements. public static class ImageHelper { public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alt) { var builder = new TagBuilder("img"); builder.GenerateId(id); // Add attributes builder.MergeAttribute("src", url); builder.MergeAttribute("alt", alt); return new MvcHtmlString( builder.ToString(TagRenderMode.SelfClosing) ); } } © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 34. Custom HTML Helper © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il

Editor's Notes

  1. http://blogs.msdn.com/b/marcinon/archive/2010/12/08/optional-razor-sections-with-default-content.aspxJust remember that you need to use the @RenderSection() syntax (you need the @ character) so that the contents of the section is actually printed to the output. Without that character you will get an exception with the following message: The following sections have been defined but have not been rendered for the layout page &quot;~/Views/Shared/_Layout.cshtml&quot;: &quot;OptionalContent&quot;
  2. http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.aspx
  3. http://msdn.microsoft.com/en-us/library/dd410596%28v=vs.98%29.aspx
  4. http://msdn.microsoft.com/en-us/library/system.web.mvc.tagbuilder.aspxhttp://www.asp.net/mvc/tutorials/using-the-tagbuilder-class-to-build-html-helpers-cs