In this and future posts, we will go over a few ASP.NET MVC interview questions. Let’s tackle Razor engine in this post.
Question: What is Asp.Net MVC Razor?
Razor is the newest view engine released by Microsoft. It’s key features include optimized Html generation, easy to learn, compact, expressive and enabling a fluid coding workflow. The Razor syntax is a template markup syntax that enables you to use an HTML construction workflow. Instead of using the ASP.NET .ASPX markup syntax with
<%= %>symbols to indicate code blocks, Razor syntax starts code blocks with a @ character and does not require explicit closing of the code-block.
With MVC 4 release, the Razor engine has been updated to better serve files. Instead of having to use path mapping methods @Url.Content to render the content of the file, you can now render using the tilde ( ~ ) character as shown below:
Question: Display some content only if a certain property in the backing model is not null.
Many times, you have the situation where you need to change the CSS property for a certain block of text only if the backing model has that info. This relatively common feature can now be simply rendered by direct html binding as shown below:
Question: How can you set the checked state of input boxes based on backing model?
This is again similar in nature to the question above. You can directly bind boolean properties of the model to Html controls.
<input checked="@Model.IsFreeShipping" type="checkbox" />
In a nutshell? Very cleanly in an intuitive way. MVC 4 has a brand new syntax to serve bundled content as shown:
@Scripts.Render("~/Scripts/cart/js") @Styles.Render("~/Content/cart/css", "~/Content/order/css")