Showing posts with label ASP.NET MVC. Show all posts
Showing posts with label ASP.NET MVC. 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>
Monday, 17 September 2012

Custom helper for surrounding a block in markup with MVC

You may have seen or used the following code in your MVC applications:
@using (Html.BeginForm())
{
    // ...
}
It surrounds the markup inside the block with a <form> tag and includes attributes based on what is passed through the parameter list. The way it works is HtmlHelper.BeginForm() returns a MvcForm object which on creation uses HtmlHelper to write markup to the page. When the using block comes to an end the Dispose method on MvcForm is used to output the closing tag.

Sunday, 5 August 2012

Func<> and Action<> basics in C#

If you've been coding in C# for a while you may have noticed the Func<> parameter type presented in several places, particularly LINQ which uses it extensively. You may know how to use it but have you ever thought about what it is exactly and how to go about using it in your own functions?

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>