How To Use Razor View Engine In Our Views

Views are actually the presentation layer of the application. With the help of Views, we see the information on the screen. Let’s start our journey.

  • We are already working on ‘HelloWorld’ project.
  • Just add a new ‘Empty Controller’ and name it ‘TestController’.
  • And add the View.

Right-click Action body > Add View.

Razor

Uncheck the layout checkbox and click on "Add".

  1. @{  
  2.     Layout = null;  
  3. }  
  4. <!DOCTYPE html>  
  5. <html>  
  6. <head>  
  7.     <meta name="viewport" content="width=device-width" />  
  8.     <title>Index</title>  
  9. </head>  
  10. <body>  
  11.     <div>   
  12.     </div>  
  13. </body>  
  14. </html>  

You already know the concept of master pages. Like in PHP files, when we are working on a page and we need headers and footers, then we make their code separate in the two different files and just include them where we need. Similarly, in Web forms, we make the master page for a common code of the page. Here, we’ve unselected the shared ‘_layout.cshtml’ page which means that the View generated through this action will run standalone. There is no dependency here in this file to any other View.

Another thing to look for is that our action name is ‘Index’ and our view name is by default ‘Index’. This is the beauty of convention in Visual Studio. It helps the developers to find out the relevant view in the same controller name folder very easily.

Now create another action but don’t generate its View.

  1. public class TestController: Controller {  
  2.     // GET: Test  
  3.     public ActionResult Index() {  
  4.         return View();  
  5.     }  
  6.     public ActionResult Demo() {  
  7.         return View();  
  8.     }  
  9. }  

Remember that

F5:              Build and Run with Debugging

Ctrl + F5:    Build and Run without Debugging

And normally I’m using Ctrl + F5.

When we request the ‘Index’ action into the URL, it shows nothing to us. Because we do not write a single line in Index-generated View, there is nothing to show on the screen. But when we request the ‘Demo’ action into the URL, then we see the error.

http://localhost:65354/Test/Demo

Let’s talk about the error.

Razor

Actually, we don’t generate its View. So it is searching the ‘Demo’ view page with any possible extension. When the file didn’t find in the folder where it should be then it will move into the Shared folder to find out same name file. This is the power of convention. The system knows that the View is of the same name as the name of the action.

Now add its view and select the ‘layout page’ checkbox.

Razor

 

Now, look, here we have a guideline in the above popup that leaves it empty if it is set in _viewstart file. But in our project, we’ve no Shared folder no _ViewStart file but still, we leave it empty. So asp.net automatically detects it and manually create all the files for us.

Click Add and now our Solution Explorer has some new files and folders which will be used to generate a well-formatted master (_layout) page with its content.

Razor

And now our view looks like

  1. @{  
  2.     ViewBag.Title = "Demo";  
  3. }<h2>Demo</h2>  

Actually in layout.cshtml there is a default theme of our application and when we trigger our action, our view ‘demo.cshtml’ which is generated with layout.cshtml will be see on the screen in good format.

Actually what is happening?

As you can see we’ve ‘_ViewStart.cshtml’ file in Views folder. It always comes into play before requesting a specific view. Here we’ve set a variable Layout

  1. @{      
  2. Layout = "~/Views/Shared/_Layout.cshtml";  
  3. }  

It means that this address is in the Layout variable. And in the views where Layout is manually set as null like in ‘Index.cshtml’ we’ll not see the styling or theme of Layout.cshtml. And in the views where it is not set to any other value or null like in ‘Demo.cshtml’  we’ll see the view in a better format.

What is @ (Razor)?

Razor is actually the view engine which is first introduced MVC 3. View Engine is responsible to render the view into html form. ASP.Net has by default 2 view engines asp.net web form view engine <% %> and razor view engine @. ASP.Net is open source so there are many 3rd party view engines as well like (Spark, Sharp Tiles, Wing Beats etc.) which we can use in our views,

Razor View EngineWeb Form View Engine
It has the file extension (.cshtml, .vbhtml)It has the file extension (.aspx, .ascx, .as)
It is advanced but it is not a new programming language.It is the classical view engine that is using from the beginning.
It prevents from attack (XSS)It doesn’t prevent an attack.
It is much slower than web form view engine.It is fast because it is near to HTML.
We use razor view [email protected]We use web form view engine.<%: DateTime.Now %>
@foreach(var item in Model) {    <tr>        <td>@item.Name</td>    </tr>}<% foreach(var item in Model) { %>    <tr>        <td><%: item.Name %></td>    </tr><% } %>

To understand the Razor view engine, we just need to understand how to use Razor and what its syntax is. We already know C#, so it would be very easy for us.

Single and Multiple Statement Blocks

This razor block starts with curly braces. Either we are using single statement or we need multiple statements. We need to enclose these statements into curly braces.

  1. @{var message = "Usama"; }  

Don’t write the statement like this:

  1. @var message = "Usama";  

It is not the way to write the single statement.

And if you are using Multiple statements then similarly:

  1. @{  
  2.     var x = 12;  
  3.     var y = 4;  
  4.     var total = x * y;  
  5. }  

I think you’re enjoying this tutorial, because it is quite easy.

Inline Statements

You don’t need to put the semicolon when you’re using these variables inline in HTML tag or between the text.

  1. <p>You total amount is @total.</p>  

Another benefit of using the razor syntax is, it has strongly typed feature. When you write @ sign and try to write the variable name you’ll see IntelliSense.

Conditional Statements

We can write conditional statements as well as to print the text conditionally on the views. It helps to make the page dynamic as well. Remember that the block statements and statements itself are enclosed in the curly braces.

  1. @if (true)  
  2. {  
  3.     <p>Salam</p>  
  4. }  
  5. else  
  6. {  
  7.     <p>WaSalam</p>  
  8. }  
  9. @{  
  10.     var isValid = true;  
  11.     if (isValid)  
  12.     {  
  13.         <p>Salam</p>  
  14.     }  
  15.     else  
  16.     {  
  17.         <p>WaSalam</p>  
  18.     }  
  19. }  

Loops

We can loop any list, any array here in the view as well. As we work in C#, we can work similarly here as well.

  1. @{  
  2.     // Array Declaration  
  3.     var nameOfDays = new[] {"Monday""Tuesday""Wednesday""Thursday""Friday"};  
  4. }  
  5. <ul>  
  6.     @foreach (var nameOfDay in nameOfDays)  
  7.     {  
  8.         <li>@nameOfDay</li>  
  9.     }  
  10. </ul>  

Don’t get confused by ‘nameOfDays’ scope, that it is declared in the above block and we can access it below in foreach as well. Remember that we’re using razor syntax just to write C# in our views file which is actually the presentation of our application.

Commenting and Uncommenting

There are some Visual Studio Keyboard Keys which are commonly used in our applications. We can comment and uncomment any kind of code with the help of these keys.

Comment:                      Ctrl + K + C

Uncomment:                  Ctrl + K + U

So just select the code which you want to comment or uncomment and just press these keys. You don’t have any need to know how to manually comment or uncomment the code with Razor syntax.

But if you’re really interested to know how to comment the code then we have two ways in Razor view engine --  Single line comment and multiple line comment.

  1. @*<li>@nameOfDay</li>*@  

We need to just put @* …..*@ signs at the start and end of the lines.

  1. @*@{  
  2.     var nameOfDays = new[] {"Monday""Tuesday""Wednesday""Thursday""Friday"};  
  3.     var hello = "Hello, World";  
  4. }*@  

Built-in Library Objects

We can also use the built-in objects which are provided by C# just for our ease. We’ll use this the same way we use razor syntax in inline statements.

  1. @DateTime.Now  
  2. @DateTime.Now.ToString("d")  

Using @: To Indicate the Start of Content

We can explicitly indicate the start of content or paragraphs between C# with the help of (@:) this syntax

  1. @if (condition)  
  2. {  
  3.     @: How are you?  
  4. }  

Twitter and Email Scenario

Maybe you’re thinking about how to write a Twitter username if we want to print it on the view.

Then don’t worry, it is so easy.

  1. @@UwaishUsama  

You need to write just double razor signs; one for the C# and another one with the Twitter id.

And in the case of email, you don’t need to worry about how to write the suffixes of the email. Because razor engine is already intelligent enough, it already knows that if razor comes between the text then the text should be printed on the screen as it is.

  1. <h1>[email protected]</h1>  

Conclusion

We’ve seen how to use razor view engine in our views. If you want to write C# multiple statements or single statement then you need to declare the razor with curly brackets.

@{}

And if you want to use this variable inline in any text or in HTML then you need to write the first razor then you’ll see the IntelliSense.

@message

If you don’t see IntelliSense, then don’t get confused because your system is slow.


Similar Articles