What is View in ASP.NET MVC?
View is responsible for UI part of the application. View is just a file located in folder that is sub folder of views folder which contains UI Code.
Link for Example Source Code: https://drive.google.com/file/d/1qgr4DKHx0swBp4BDDD2ul0MBd42t1Fhl/view?usp=sharing
View Can contain the UI code it can be server side code with C# and Client Side Code like CSS/HTML/ Images etc.
Their is no url mapped to view in ASP.NET MVC view, url’s are always mapped to action from controller and then action can return a View if the return type of the action is ViewResult.
Action can return a view using following method –
- View() :- return a view having same name as that of action and in folder having same name as that of controller name or in a folder in shared folder.
- View(“View Name”) :- This is similar to above method but returns a view with name passed as parameter.
What is View Engines? How to use the Razor?
Example Source Code: https://drive.google.com/file/d/1Cmt7f_sQg3l1i9mmQRhmVqFepmYJ-E-s/view?usp=sharing
View Engines in ASP.NET MVC are the programs/plugins is used to translate our views to HTML/CSS and render them to the browser.
By default, ASP.NET MVC supports ASPX and Razor View Engine. ASP.NET MVC 1,2,3,4 having ASPX View Engine and from ASP.NET MVC 3 onward’s Microsoft Introduce Razor View Engine and ASP.NET MVC 5 has only Razor View Engine.
Indirectly we can say View Engines enables you to embed server side code in View. View Engines provides facilities using which we can embed server side code in view.
What are the advantages of Razor View Engine?
- Provide commands to embed server side code in view.
- Clean and Easy to use or understand Syntax, require less number of keystrokes.
- Support Test Driven Development.
- Automatic HTML encoding to avoid cross site script attacks.
- Intelligent to switch from server side code to html.
Few Razor Commands or Syntax
Every razor code starts with @ and will have following commands –
@varaiblename to embed or display value of the variable or property in html code.
@* comment *@ used for the comment.
@:text is used to embed text in razor code.
text is used to embed text in razor code.
@@ to embed the @ in razor code.
@if(condition){ if code } else { else code}
@for(initialisation;terminating condition; increment/decrement) { code }