Showing posts with label Razor. Show all posts
Showing posts with label Razor. Show all posts
Thursday, 20 December 2012

Use razor comments in MVC views not HTML comments

Make sure for code documentation you use the razor-style comments in your ASP.NET MVC views, not HTML-style comments. Regular HTML comments will be sent to the client which would increase the page size and expose unnecessary implementation details to the end-user, razor comments are kept server-side.

Good:
@* Comment *@

Bad:
<!-- Comment -->
Sunday, 16 December 2012

ASP.NET MVC display and editor templates

Display templates

MVC has a bunch of handy helpers that we can use to create our views more efficiently. One such helper are the display templates that are used within views.

@Html.DisplayFor(e => e.Username)

The DisplayFor(Func<TModel, TValue> expression) function uses the type of the property in the expression to display the property value.

<!-- DisplayFor on string UserName = "daniel.imms" -->
<span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true">daniel.imms</span>
Saturday, 4 August 2012

Using razor within an Umbraco template

Normally you restrict use of razor to the scripting folder in the developer tab and expose them via macros, but you can also use them inside a template by creating an inline macro like so:
<umbraco:Macro runat="server" Language="razor">
@{
    // insert razor here
    var href = "index.htm";
    <a href="@href">Home</a> 
} 
</umbraco:Macro>
This should only be done for small one-offs where you are unlikely to need to reuse the functionality, such as loading in the page title. Keep anything greater than that in the scripting folder.
Tuesday, 24 July 2012

ASP.NET MVC inline functions in a razor view

Here is the syntax for defining inline functions in an ASP.NET MVC razor view. I found this particularly useful when working with Umbraco as the regular alternatives like extension methods and helper classes aren't available.
@functions
{
    HtmlString PrintSomething()
    {
        return new HtmlString("Hello World");
    }
}
Returning a HtmlString object will allow you to print to the screen.
<div>@PrintSomething()</div>