Monday, December 3, 2012

How to declare local variable in ASP.NET MVC Razor?

Issue:
How to declare local variable in ASP.NET MVC Razor?
This is a very common scenario that newbies in ASP.NET MVC Razor view comes across.
It would be confusing when even with the "@" sign before the declaration it doesn't work.

Solution:
The solution as simple as placing the whole declation statement inside curly braces.
Even multiple declarations can be placed inside a curly braces block.
The declaration and usage would be as below.

@{int count = 1;}
@foreach (var step in level.steps)
{
    <div>
        <span class="title">@step.Name</span>
        <span class="meaning">@step.Description</span>
    </div>
}

No comments:

Post a Comment