TOC

The community is working on translating this tutorial into Tamil, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Razor:

Variables

Just like in regular C# code, you can define variables in Razor, to store information for later use. If you are already inside a code-scope, e.g. inside an if-statement or another control structure, you can just define it straight away. If you're inside of a markup-scope, you can use a Razor code-block, as described in a previous article, to define your variable inside. Here's an example:

@{ 
    string helloWorldMsg = "Hello, world!";
}

You can of course output it just as easily, either directly in the code block or outside of it, by referencing the name. Here's an example of it:

@{ 
    string helloWorldMsg = "Hello, world!";
}

<div>
    @helloWorldMsg
</div>

You can of course work with and manipulate your variables and apply logic to them, just like you would in C#:

@{ 
    string helloWorldMsg = "Good day";
    if(DateTime.Now.Hour > 17)
    {
helloWorldMsg = "Good evening";
    }
    helloWorldMsg += ", world!";
    helloWorldMsg = helloWorldMsg.ToUpper();
}

<div>
    @helloWorldMsg
</div>

Summary

Declaring and using variables in Razor is just as easy as using them in your regular C# code. As you will see in later examples, it can be really powerful to have easy-access to variables in your markup.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!