• How to Build HTML Views using Razor View Engine in ASP.NET MVC

    by  • December 31, 2015 • Microsoft .NET C# (C-Sharp), Microsoft ASP.NET MVC • 0 Comments

    View Engine is responsible for rendering the View to the browser in the form of HTML.  By default there are two view engines in ASP.NET MVC4. First is ‘Webform’ and second is ‘Razor’. Razor is a markup syntax that lets u to embed server side code into your HTML Markup code. When a view is called, the server executes the server side code inside the view before it returns the page to the browser.

    Razor Syntax rules for C# is given below;

    • Razor code block is enclosed in @ {…..}
    • Variables are declared with the var keyword
    • Code statement ends with Semi
    • Strings are enclosed in quotation marks

    Now lets look at the following code examples;

    Single Statement Block

    In this example we declared the variable named as message and assign a value string type to it that is Welcome All. Then we access its value in the html markup code by using @ character. Its output is shown below;
    Razor Syntax

    Multi Statement Block

    In the above code we declared two variables num1 and num2, and put the sum of these two variables in the third variable called result. The output is given below;


    Conditional Statement

    In conditional statement, a particular part of code is executed base on certain condition or state is met. The output is shown below;


    Looping Constructs 

    In above code, the value of i will print until the condition in for loop (i<8) is true. And in the foreach loop we declare a variable i that represent single item in the collection followed by the in keyword followed by the collection name we want to loop through. The output is shown below;



    Comments allow us to prevent the section of code that we dont want to run but want to keep in our page for time being. In the above code we prevent first part of for loop code from execution. Comments start with @ sign followed by * and end with * followed by @ sign. Output is shown below;




    Leave a Reply